【问题标题】:while read two lines as one string variable而将两行作为一个字符串变量读取
【发布时间】:2012-07-08 00:20:04
【问题描述】:

这是我想要做的: 我有一个以下命令:

result=`awk /^#.*/{print;getline;print} file1.txt
echo "$result"

输出是:

#first comment
first line
#second comment
second line
#third comment
third line.

如果我必须将 $result 放入 while 循环并捕获两行作为一个字符串变量并打印它,我该怎么做?

例子:

echo "$result" | while read m
do
echo "Value of m is: $m"
done

输出是:

Value of m is:#first comment
Value of m is:first line
Value of m is:#second comment
Value of m is:second line
Value of m is:#third comment
Value of m is:third line.

但预期的输出是:

Value of m is:
#first comment
first line
Value of m is:
#second comment
second line
Value of m is:
#third comment
third line.

【问题讨论】:

    标签: string bash shell awk while-loop


    【解决方案1】:
    while read -r first; read -r second
    do
        printf '%s\n' 'Value of m is:' "$first" "$second"
    done
    

    或者如果您需要变量中的行:

    while read -r first; read -r second
    do
        m="$first"$'\n'"$second"
        echo 'Value of m is:'
        echo "$m"
    done
    

    【讨论】:

    • 这行得通,但我会使用命令分组来使正在发生的事情更加清晰,例如while { read -r first; read -r second; } do.
    • 这很好用,感谢 CodeGnome 的建议,我使用了同样的方法。
    【解决方案2】:

    使用awk 的一种方式。在每个奇数行中读取下一行并将它们连接在换行符之间。

    awk '
        FNR % 2 != 0 { 
            getline line; 
            result = $0 "\n" line; 
            print "Value:\n" result; 
        }
    ' infile
    

    假设infile的内容为:

    #first comment
    first line
    #second comment
    second line
    #third comment
    third line.
    

    运行之前的awk 命令输出将是:

    价值:

    Value:
    #first comment
    first line
    Value:
    #second comment
    second line
    Value:
    #third comment
    third line.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 2018-03-03
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多