问题
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 read
s 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