views:

65

answers:

3

file.txt contains:

##w##

##wew##

using mac 10.6, bash shell, the command:

cat file.txt | grep [[:alpha:]]* -o

outputs nothing. I'm trying to extract the text inside the hash signs. What am i doing wrong?

+2  A: 

(Note that it is better practice in this instance to pass the filename as an argument to grep instead of piping the output of cat to grep: grep PATTERN file instead of cat file | grep PATTERN.)

What shell are you using to execute this command? I suspect that your problem is that the shell is interpreting the asterisk as a wildcard and trying to glob files.

Try quoting your pattern, e.g. grep '[[:alpha:]]*' -o file.txt.

I've noticed that this works fine with the version of grep that's on my Linux machine, but the grep on my Mac requires the command grep -E '[[:alpha:]]+' -o file.txt.

RTBarnard
already did, no luck. double quotes don't fix it either.neither does `'[[:alpha:]]'*` (enclosing only the [[:alpha:]] field in quotes)
adam n
Interestingly, this solution works fine on one of my Linux machines, but not on my Mac. On the Mac it works fine if I use the -E flag and + instead of *: grep -E '[[:alpha:]]+' -o.
RTBarnard
Also, you should note that in bash, a `*` in double-quotes will still cause globbing. Single-quotes tells the shell not to interpret the quote's contents. So you'll want your whole RE to be nested in single-quotes.
RTBarnard
`[[:alpha:]]*` matches every line because every line will always contain 0 or more alphabetic characters.
dreamlax
+1  A: 
sed 's/#//g' file.txt

/SCRIPTS [31]> cat file.txt
##w##
##wew##

/SCRIPTS [32]>  sed 's/#//g' file.txt
w
wew
Vijay Sarathi
yeah, i thought of that, but it just annoyed me that the grep way didn't work.
adam n
For this application, grep is probably a better choice than sed because its performance will be noticably better. Discussions of sed/grep performance abound on the web, but in an informal test, I ran 500 iterations using sed and 500 using grep. Running this test 10 times, sed averaged ~2.2s to complete, while grep averaged ~1.5s to complete.
RTBarnard
A: 

if you have bash >3.1

while read -r line
do
  case "$line" in
   *"#"* )
        if [[ $line =~ "^#+(.*)##+$" ]];then
            echo ${BASH_REMATCH[1]}
        fi
  esac    
done <"file"
ghostdog74