这是我想要做的: 我有一个以下命令:
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.
答案 0 :(得分: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
答案 1 :(得分: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.