203

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
  • 6
    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")
    – Adam Katz
    Commented Dec 14, 2016 at 21:02

7 Answers 7

352

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)
7
  • if there is no line with xyz ?
    – XYZ_Linux
    Commented May 1, 2013 at 12:24
  • Then nothing happens, the loop is not run.
    – Mat
    Commented May 1, 2013 at 12:26
  • 17
    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! Commented Jan 24, 2014 at 15:50
  • 4
    @David: provided an alternative to address your concern. (fedorqui had already addressed it too.)
    – Mat
    Commented Jan 24, 2014 at 15:52
  • 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/…) Commented Feb 22, 2016 at 9:59
29

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
  • 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.
    – fedorqui
    Commented May 1, 2013 at 15:36
  • 1
    You can't apply parameter expansion to a command substitution (unless you're using zsh, where that kind of nesting probably works).
    – chepner
    Commented May 1, 2013 at 15:39
  • 1
    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 ... Commented Jun 13, 2019 at 20:46
  • 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.
    – zypA13510
    Commented Apr 9, 2021 at 11:03
24

For those looking for a one-liner:

grep xyz abc.txt | while read -r line; do echo "Processing $line"; done
1
  • 2
    rly needed this thanks a lot <3
    – YESSINE
    Commented Jan 12, 2022 at 7:50
9

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

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

2
  • 1
    How would you reference the complete found line in //your code goes here?
    – user857990
    Commented Dec 3, 2013 at 14:58
  • 2
    @user857990 The whole line is represented as $0 in AWK. Commented Dec 4, 2013 at 23:22
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
  • The only solution that works if your_command is long-running (such as tail -f some.log, in my case)...
    – Izkata
    Commented Sep 27, 2019 at 18:28
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
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

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