2012-07-08 56 views
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
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

这工作,但我会用命令 - 分组以使得发生的事情更清楚一些,例如'while {read -r first;读-r秒; }做'。 – 2012-07-08 09:14:16

+0

这工作太棒了,谢谢你的建议CodeGnome我使用了相同的。 – phani 2012-07-08 15:33:06

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. 
+0

感谢您的建议。 – phani 2012-07-09 18:00:36

相关问题