Leon WANG
Leon WANG

Reputation: 103

grep did not search properly

In my Perl scripts, I run bash code below

$tmp=`grep -E -n 'FRAME.*$atom_id'\$'\\s{1,}''$spc_lbl{$all_species}' $file_o_nghb_refine |wc -l`

where, $tmp, $atom_id, $spc_lbl[], $all_species are variables or elements of an array. Normally (all other files show the result properly except one file, all files are generated by my program without any interruption), the result would show values like below if removing "wc -l"

FRAME     0 11687 Fe  7744AL 
FRAME     1 11687 Fe  7744AL 
FRAME     2 11687 Fe  7744AL 
FRAME     3 11687 Fe  7744AL 
FRAME     4 11687 Fe  7744AL 
FRAME     5 11687 Fe  7744AL 
FRAME     6 11687 Fe  7744AL 
FRAME     7 11687 Fe  7744AL 
FRAME     8 11687 Fe  7744AL 
FRAME     9 11687 Fe  7744AL 
FRAME    10 11687 Fe  7744AL 
......

However, above code cannot show one file properly. In fact, if I use bash code directly,
grep 'FRAME 0 11687'$'\s{0,}''Fe' 15x200.lammpstrj.o_neighbors.raw.dat I could not find the results, either. If I use

grep 'FRAME.*11687.*Fe' 15x200.lammpstrj.o_neighbors.raw.dat

The results would be shown like above.

Is there anything wrong or improperly? How can I improve the scripts? Why the same scripts could work for the other files except for this one? Any further suggestion would be highly appreciated.

Upvotes: 2

Views: 70

Answers (1)

Jens
Jens

Reputation: 72639

The directly used bash code can't work, because $'\s{0,}' does not what you think it does. The $'...' interpolates C escape sequences, e.g. $'\n' expands to a newline. $'\s' is simply undefined and substituted as \s. If you need to grep for zero or more space characters, use

grep '...[[:space:]]*...'

Upvotes: 1

Related Questions