1

I have a funny issue with grep. Basically, I am trying to match certain control characters in a file and get the count.

grep -ocbUaE $"\x07\|\x08\|\x0B\|\x0C\|\x1A\|\x1B" <file>

Funny enough, in CLI it matches all control characters and returns the correct count, but if I use it in a bash script, it doesn't match anything.

Any ideas what I am doing wrong?

Tested on: MacOS and CentOS - same issue.

Thank you for your help!

Ionut
  • 11
  • 1
  • I'm confused by `$""` (since you have no variables) and the long list of switches you're passing to grep. Surely you only need `-cE`? Is it possible that you're running interactively in Bash and just using `sh` to run the script? – Tom Fenech Jul 24 '18 at 13:44
  • Hi Tom, thank you for answering. Yes, you are right about the fact the -cE would be enough. The $ in front is used for control characters and yes I am running the script interactively in Bash with sh. But I don't understand why I get 2 different results... – Ionut Jul 24 '18 at 13:49
  • see also https://stackoverflow.com/questions/5725296/difference-between-sh-and-bash .. and `-U` is only useful on `MS-DOS and MS-Windows` as per man page – Sundeep Jul 24 '18 at 14:46

1 Answers1

3

I think you should change your command to:

grep -cUaE $'[\x07\x08\x0B\x0C\x1A\x1B]' file

I removed the extra output flags, which get ignored when -c is present. I assume that you include -U and -a for a reason.

The other changes are to use $'' with single quotes (you don't want a double-quoted string here), and replace your series of ORs with a bracket expression, which matches if any one of the characters match.

Note that C-style strings $'' don't work in all shells, so if you want to use bash you should call your script like bash script.sh and/or include the shebang #!/bin/bash if it is executable. sh script.sh does not behave in the same way as bash script.sh.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • Thank you for the detailed explanation and also for the command :). I confirm it works as expected and I get the same result from CLI and script. – Ionut Jul 24 '18 at 14:12
  • @Ionut you're welcome. If you haven't already read [someone-answers](https://stackoverflow.com/help/someone-answers), I recommend that you do so! – Tom Fenech Jul 24 '18 at 14:28