1

这是我正在尝试做的事情:我有一个以下命令:

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

2 回答 2

4
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
于 2012-07-08T06:41:18.970 回答
1

一种使用方式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.
于 2012-07-08T09:45:14.883 回答