0

I could search lines that contain two specific words using the following in multiple files:

for f in $(ls *.txt); do
  echo ">"$f; more $f | grep word1 | grep word2
done

Now, I want to write a shell script to accomplish this so that I don't have to retype the whole thing again and again. I also wanted to add an option of using either one word or two words in the search. I will be passing these searched word to the shell script at the command line. I wrote the following shell script searchwords.sh:

word1=$1
word2=$2
for f in $(ls *.txt); do
echo ">"$f
###if word2 is empty; then execute 
if [-z $word2]; then
        more $f | grep $word1
else
###if word2 is not empty
        more $f | grep $word1 | grep $word2
fi
done

Usage:

sh searchwords.sh word1 word2

Although I got what I want, I am also getting an error ouput

[-z: not found

I know my code is not right, but I cannot place it.

  • You need a space after the [. Further, a) ls *.txt is broken (for f in *.txt will work), b) more | grep is a pretty bizarre way of giving grep some input. – Michael Homer Apr 14 '15 at 2:48
1

There are some mistakes in your script:

  • Missing space in [-z $word2]
  • Missing double quote in variables
  • Useless use of more | grep
  • Parsing output of ls is broken
  • grep will fail if $word1 or $word2 start with dash -

Here's a fix:

word1=$1
word2=$2

for f in ./*.txt; do
  printf '>%s\n' "$f"

  ###if word2 is empty; then execute 
  if [ -z "$word2" ]; then
    grep -- "$word1" "$f"
  else
  ###if word2 is not empty
    grep -- "$word1" "$f" | grep -- "$word2"
  fi
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.