bash 用 ifs 分割行后打印整行
bash print whole line after splitting line with ifs
当 awk
使用定界符将一行拆分为多个字段时,它会在 [=14=]
变量中保留原始行。因此它可以在对各个字段执行操作后打印原始行(假设没有其他内容修改 [=14=]
)。 bash 的 read
是否可以做类似的事情,它不仅有单个元素,还有整行?
例如,使用以下 input.txt
foo,bar
baz,quz
我试图在 bash 中模仿的 awk
行为是:
awk -F, '( == "baz") {print [=19=]}' input.txt
这将打印 baz,quz
因为 [=14=]
是读取的整行,即使该行也被分成两个字段(</code> 和 <code>
) .
Bash:
while IFS=, read -r first second; do
if [[ "$first" == lemur ]]; then
# echo the entire line
fi
done < input.txt
在这个简单的例子中,通过在 $first
和 $second
变量之间用逗号回显来重新创建原始行并不太难。但是在 IFS
可能不止一个字符并且可能有很多字段的更复杂的场景中,除非 bash 否则准确地重新创建原始行变得更加困难在读取操作期间维护它。
可能你必须用 2 个不同的 read
来完成它,比如
while read -r line; do
IFS=, read first second <<<"$line"
if [[ $first == lemur ]]; then
printf '%s\n' "$line"
fi
done < input.txt
当 awk
使用定界符将一行拆分为多个字段时,它会在 [=14=]
变量中保留原始行。因此它可以在对各个字段执行操作后打印原始行(假设没有其他内容修改 [=14=]
)。 bash 的 read
是否可以做类似的事情,它不仅有单个元素,还有整行?
例如,使用以下 input.txt
foo,bar
baz,quz
我试图在 bash 中模仿的 awk
行为是:
awk -F, '( == "baz") {print [=19=]}' input.txt
这将打印 baz,quz
因为 [=14=]
是读取的整行,即使该行也被分成两个字段(</code> 和 <code>
) .
Bash:
while IFS=, read -r first second; do
if [[ "$first" == lemur ]]; then
# echo the entire line
fi
done < input.txt
在这个简单的例子中,通过在 $first
和 $second
变量之间用逗号回显来重新创建原始行并不太难。但是在 IFS
可能不止一个字符并且可能有很多字段的更复杂的场景中,除非 bash 否则准确地重新创建原始行变得更加困难在读取操作期间维护它。
可能你必须用 2 个不同的 read
来完成它,比如
while read -r line; do
IFS=, read first second <<<"$line"
if [[ $first == lemur ]]; then
printf '%s\n' "$line"
fi
done < input.txt