bash print whole line after splitting line with ifs

浪子不回头ぞ 提交于 2019-12-13 15:15:37

问题


When awk splits a line into fields using a delimiter, it maintains the original line in the $0 variable. Thus it can print the original line (assuming nothing else modifies $0) after performing operations on the individual fields. Can bash's read do something similar, where it has not only the individual elements but also the entire line?

E.g., with the following input.txt

foo,bar
baz,quz

The awk behavior that i'm trying to imitate in bash is: awk -F, '($1 == "baz") {print $0}' input.txt

This will print baz,quz because $0 is the whole line that was read, even though the line was also split into two fields ($1 and $2).

Bash:

while IFS=, read -r first second; do
   if [[ "$first" == lemur ]]; then
      # echo the entire line
   fi
done < input.txt

In this simple case it wouldn't be too difficult to recreate the original line by echoing the $first and $second variables with a comma between them. But in more complex scenarios where IFS may be more than one character and there may be many fields, it becomes much harder to accurately recreate the original line unless bash is maintaining it during the read operation.


回答1:


Probably you'll have to do it with 2 different reads like

while read -r line; do
    IFS=, read first second <<<"$line"

    if [[ $first == lemur ]]; then
        printf '%s\n' "$line"
    fi
done < input.txt


来源:https://stackoverflow.com/questions/52503935/bash-print-whole-line-after-splitting-line-with-ifs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!