By default, grep
uses Basic Regular Expressions (BRE) which don't support {N}
. If it works on the commandline, you most probably have grep
aliased to grep -E
or grep -P
. You can check by running
alias | grep grep
Aliases are not enabled in scripts. As explained in man bash
:
Aliases are not expanded when the shell is not interactive, unless the
expand_aliases shell option is set using shopt.
So, in a non-interactive shell, which is what you get when you run a script, aliases won't work. You have two options, either enable the aliases explicitly in your script and then source your ~/.bashrc
file to get the alias definitions (there's no need to escape the ,
, by the way):
#!/bin/bash
shopt -s expand_aliases
source ~/.bashrc
grep -o ',[a-z][a-z0-9]{1,7}' source.txt > test.txt
Or, far simpler, use grep -E
in the script itself:
#!/bin/bash
grep -Eo ',[a-z][a-z0-9]{1,7}' source.txt > test.txt
You might also want to consider tools like awk
that are designed to work on field-delimited data though. Chances are they will make your life much simpler.
type grep
return? Do you have an aliasgrep='grep -E'
orgrep=egrep
?{1,7}
is extended RE syntax only recognised with-E
.set -x
mode into the script.alias grep='grep -E'
, that's silly.grep
butcut -d, -f5
?