Reputation: 181
I want to run 2 different greps sequentially on each line in a file so that it will output the matches in the order that occurred in the input file. I have a simple file called temp.txt that I will use for this example. Contents of this file are:
$ cat temp.txt
line1 a
line2 b
line3 c
I have the following code which I have simplified by using an echo instead of the first grep.
#! /bin/bash
cat temp.txt | while read line
do
echo $line
grep b $line
done
I thought the output would have been:
line1 a
line2 b
line2 b
line2 c
But I am getting the following output:
$ ./debug.sh
line1 a
grep: line1: No such file or directory
grep: a: No such file or directory
line2 b
grep: line2: No such file or directory
grep: b: No such file or directory
line3 c
grep: line3: No such file or directory
grep: c: No such file or directory
Upvotes: 1
Views: 166
Reputation: 62439
Perhaps you should only run one grep
, but give it both patterns to look for:
grep 'pattern1\|pattern2' file.txt
Upvotes: 2
Reputation: 59250
Your script should look like this
#! /bin/bash
cat temp.txt | while read line
do
echo $line
grep b <<< "$line"
done
to get the output you want. grep
is expecting input from a file or from stdin
. Your syntax makes grep
think it has to open a file. This version makes sure the $line
is fed to its stdin
.
Upvotes: 0
Reputation: 290025
You have to do something like:
#! /bin/bash
while read line
do
echo "$line" | grep "b"
done < temp.txt
Or instead of echo "$line" | grep "b"
you can also use:
grep "b" <<< "$line"
In your case,
grep b $line
was trying to grep b
on a file called $line
, which obviously does not exist.
Note there is no need to cat
the file and pipe to the while
: while read ... done < file
makes it.
Upvotes: 1