linux - Error while comparing in shell -


i trying search pattern(trailer) , if occures more once in file, need filenames displayed

    f in *.txt          if((tail -n 1 $f | grep '[9][9][9]*' | wc -l) -ge 2);              echo " file $f has more 1 trailer"      fi     done 

your crying syntax error -ge operator [ … ] or [[ … ]] conditional construct. doesn't have chance way wrote program. -ge needs number on both sides, , have on left command. meant have output of command, need command substitution syntax: $(…). that's

if [ $(tail -n 1 $f | grep '[9][9][9]*' | wc -l) -ge 2 ]; 

this syntactically correct never match. tail -n 1 $f outputs 1 line (unless file empty), grep sees @ 1 line, wc -l prints either 0 or 1.

if want search pattern on more 1 line, change tail invocation. while you're @ it, can change grep … | wc -l grep -c; both same thing, count matching lines. example, search in last 42 lines:

if [ $(tail -n 42 -- "$f" | grep -c '[9][9][9]*') -ge 2 ]; 

if want search 2 matches on last lines, that's different. grep won't because determines whether each line matches or not, doesn't multiple matches per line. if want multiple non-overlapping matches on last line, repeat pattern, allowing arbitrary text in between. you're testing if pattern present or not, need test return status of grep, don't need output (hence -q option).

if tail -n 1 -- "$f" | grep -q '[9][9][9]*.*[9][9][9]*'; 

i changed tail invocations add -- in case file name begins - (otherwise, tail interpret option) , have double quotes around file name (in case contains whitespace or \[*?). these habits into. put double quotes around variable substitutions "$foo" , command substitutions "$(foo)" unless know substitution result in whitespace-separated list of glob patterns.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -