207

I have a number of lines retrieved from a file after running the grep command as follows:

var=`grep xyz abc.txt`

Let’s say I got 10 lines which consists of xyz as a result.

Now I need to process each line I got as a result of the grep command. How do I proceed for this?

1
  • 7
    None of the answers here mention the power of grep -o for this sort of thing. The -o flag will give back only the text that matches, with one match per line of output. (It's not exhaustive, so echo aaa |grep 'a*' only gives you "aaa" and omits the three partial matches "", "a", and "aa") Commented Dec 14, 2016 at 21:02

7 Answers 7

356

One of the easy ways is not to store the output in a variable, but directly iterate over it with a while/read loop.

Something like:

grep xyz abc.txt | while read -r line ; do
    echo "Processing $line"
    # your code goes here
done

There are variations on this scheme depending on exactly what you're after.

If you need to change variables inside the loop (and have that change be visible outside of it), you can use process substitution as stated in fedorqui's answer:

while read -r line ; do
    echo "Processing $line"
    # your code goes here
done < <(grep xyz abc.txt)
Sign up to request clarification or add additional context in comments.

7 Comments

if there is no line with xyz ?
Then nothing happens, the loop is not run.
The problem with this method is that (because of the pipe) everything inside the loop is in a subshell, so setting variables defined outside the loop during the loop does not make their values available after the loop!
@David: provided an alternative to address your concern. (fedorqui had already addressed it too.)
For commands whose last line of output is not terminated with a newline, you'd need: while read p || [[ -n $p ]]; do ... (borrowed from stackoverflow.com/questions/1521462/…)
|
30

You can do the following while read loop, that will be fed by the result of the grep command using the so called process substitution:

while IFS= read -r result
do
    #whatever with value $result
done < <(grep "xyz" abc.txt)

This way, you don't have to store the result in a variable, but directly "inject" its output to the loop.


Note the usage of IFS= and read -r according to the recommendations in BashFAQ/001: How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?:

The -r option to read prevents backslash interpretation (usually used as a backslash newline pair, to continue over multiple lines or to escape the delimiters). Without this option, any unescaped backslashes in the input will be discarded. You should almost always use the -r option with read.

In the scenario above IFS= prevents trimming of leading and trailing whitespace. Remove it if you want this effect.

Regarding the process substitution, it is explained in the bash hackers page:

Process substitution is a form of redirection where the input or output of a process (some sequence of commands) appear as a temporary file.

4 Comments

OK, I striked the for version. Tried to do a loop on "${$(grep xyz abc.txt)[@]}" as in stackoverflow.com/a/14588210/1983854 but could not. So I just leave the first version.
You can't apply parameter expansion to a command substitution (unless you're using zsh, where that kind of nesting probably works).
One possible problem with this idiom is that if anything inside the loop tries to read from standard input, it'll get part of the file. To avoid this possibility, I like to send the file through file descriptor 3 rather than stdin. Just use while IFS= read -r result <&3 and done 3< <(grep ...
I know the original question asked for bash, but for future readers: this is not POSIX-compliant. shellcheck(SC2039): In POSIX sh, process substitution is undefined.
23

For those looking for a one-liner:

grep xyz abc.txt | while read -r line; do echo "Processing $line"; done

Comments

9

I would suggest using awk instead of grep + something else here.

awk '$0~/xyz/{ //your code goes here}' abc.txt

2 Comments

How would you reference the complete found line in //your code goes here?
@user857990 The whole line is represented as $0 in AWK.
2

Without any iteration with the --line-buffered grep option:

your_command | grep --line-buffered "your search"

Real life exemple with a Symfony PHP Framework router debug command ouput, to grep all "api" related routes:

php bin/console d:r | grep --line-buffered "api"

1 Comment

The only solution that works if your_command is long-running (such as tail -f some.log, in my case)...
2

Iterate over the grep results with a while/read loop. Like:

grep pattern filename.txt | while read -r line ; do
    echo "Matched Line:  $line"
    # your code goes here
done

Comments

0

Often the order of the processing does not matter. GNU Parallel is made for this situation:

grep xyz abc.txt | parallel echo do stuff to {}

If you processing is more like:

grep xyz abc.txt | myprogram_reading_from_stdin

and myprogram is slow then you can run:

grep xyz abc.txt | parallel --pipe myprogram_reading_from_stdin

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.