文字列から行の列にアクセスするには?

文字列から行の列にアクセスするには?

繰り返しているファイルがありますfor。次のようなことをしたいのですが…

for line in file.out; do echo "Some text before $line($2) $line($3)"; done

ここでは、各行について、その行の2番目と3番目の列を現在の文字列に挿入します。これを行う簡単な方法はありますか?文字列からawkにアクセスできますか?

入力例:

some.metric.tag_A 100500 1446043920
some.metric.tag_B 100501 1446043921
some.metric.tag_C 100502 1446043922
some.metric.tag_D 100503 1446043923

出力例:

Some text before 100500 1446043920
Some text before 100501 1446043921
Some text before 100502 1446043922
Some text before 100503 1446043923

ベストアンサー1

awkを使う

awk は行を暗黙的に繰り返し、各行をフィールドに分割します。

$ awk '{printf "Some text before %s %s\n",$2,$3}' file.out
Some text before 100500 1446043920
Some text before 100501 1446043921
Some text before 100502 1446043922
Some text before 100503 1446043923

入力ファイルに常に3つの列しかないことがわかっている場合は、このコマンドを次のように短縮できます。 (ヒント:Don Crissti)

$ awk '{$1="Some text before"} 1' file.out

シェルを使う

シェル文を使用して行をreadフィールドに分割できます。

$ while read a b c d; do echo "Some text before $b $c" ; done <file.out
Some text before 100500 1446043920
Some text before 100501 1446043921
Some text before 100502 1446043922
Some text before 100503 1446043923

おすすめ記事