【发布时间】:2017-03-31 20:10:21
【问题描述】:
我正在学习 bash。我想一次通过 grep 获取返回值和匹配行。
if cat 'file' | grep 'match_word'; then
match_by_grep="$(cat 'file' | grep 'match_word')"
read a b <<< "${match_by_grep}"
fi
在上面的代码中,我使用了两次 grep。我想不出一次如何通过 grep 来做到这一点。即使没有匹配的单词,我也不确定 match_by_grep 是否始终为空,因为 cat 可能会输出错误消息。
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
请告诉我怎么做。非常感谢。
【问题讨论】:
-
提供样本输入和预期输出
-
显示输入,预期输出。
-
附带说明,最好使用
grep pattern file而不是cat file | grep pattern