mora mora - 16 days ago 10
Bash Question

How can I get the return value and matched line by grep in bash at once?

I am learning bash. I would like to get the return value and matched line by grep at once.

if cat 'file' | grep 'match_word'; then
match_by_grep="$(cat 'file' | grep 'match_word')"
read a b <<< "${match_by_grep}"
fi


In the code above, I used grep twice. I cannot think of how to do it by grep once. I am not sure match_by_grep is always empty even when there is no matched words because cat may output error message.

match_by_grep="$(cat 'file' | grep 'match_word')"
if [[ -n ${match_by_grep} ]]; then
# match_by_grep may be an error message by cat.
# So following a and b may have wrong value.
read a b <<< "${match_by_grep}"
fi


Please tell me how to do it. Thank you very much.

Answer

You can avoid the double use of grep by storing the search output in a variable and seeing if it is not empty.

Your version of the script without double grep.

#!/bin/bash

grepOutput="$(grep 'match_word' file)"

if [ ! -z "$grepOutput" ]; then
    read a b <<< "${grepOutput}"
fi

An optimization over the above script ( you can remove the temporary variable too)

#!/bin/bash

grepOutput="$(grep 'match_word' file)"

[[ ! -z "$grepOutput" ]] && (read a b <<< "${grepOutput}")

Using double-grep once for checking if-condition and once to parse the search result would be something like:-

#!/bin/bash

if grep -q 'match_word' file; then
    grepOutput="$(grep 'match_word' file)"
    read a b <<< "${grepOutput}"
fi
Comments