1

これが私がやろうとしていることです:私は次のコマンドを持っています:

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

出力は次のとおりです。

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

$result を while ループに入れ、2 行を 1 つの文字列変数としてキャプチャして出力する必要がある場合、どうすればよいですか?

例:

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 に答える