本文介绍了bash用ifs分割行后打印整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

awk 使用定界符将行拆分为字段时,它将原始行保留在 $ 0 变量中。因此,在对各个字段执行操作之后,它可以打印原始行(假设没有其他修改 $ 0 )。 bash的 read 可以做类似的事情吗,它不仅具有单个元素,而且具有整个行?

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?

例如,以及以下 input.txt

foo,bar
baz,quz

awk 行为我想模仿bash是:
awk -F,'($ 1 == baz){print $ 0}'input.txt

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

这将打印 baz,quz ,因为 $ 0 是整体读取的行,即使该行也被分成两个字段( $ 1 $ 2 )。

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).

重击:

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

在这种简单情况下,通过回显来重新创建原始行并不难 $ first $ second 变量之间用逗号隔开。但是在更复杂的情况下,其中 IFS 可能不止一个字符并且可能有很多字段,除非 bash ,否则要准确地重新创建原始行会变得更加困难。

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.

推荐答案

可能您必须使用2个不同的<$ c $来完成它。 c>读取,例如

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

这篇关于bash用ifs分割行后打印整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:21