他のファイルのテキストをコマンドとして使用する

他のファイルのテキストをコマンドとして使用する

ファイルからデータを抽出して正しい形式で出力する作業方法を見つけようとしています。

data.txtというファイルがあり、次のようなものであるとします。

abc 123
def 456

その後、スクリプトを使用してデータを解析し、次のようにレンダリングしたいと思います。

first abc second 123
third def fourth 456

これまで私はこれを作りました:

#!/bin/sh
#

for i in data.txt; do while read -r a b; do
    echo "First $a second $b"
    echo "third $a fourth $b"

done < data.txt
done

出力は次のとおりです。

First abc second 123
third abc fourth 123
First def second 456
third def fourth 456

したがって、各行を読み取り、一度適用し、data.txtから次の行に移動するのではなく、次のechoコマンドに同じデータを適用し続け、次の行に移動します。私はおそらく簡単なことを見落としていることを知っていますが、本当に長い一日でした。 :)

ベストアンサー1

ループで2回の読み取りを実行できます。

#!/bin/sh

while read -r a b && read -r c d; do
  echo "First $a second $b"
  echo "third $c fourth $d"
done < data.txt

実際のアプリケーションに応じてxargsex。

xargs -L2 /bin/printf 'First %s second %s\nthird %s fourth %s\n' < data.txt

おすすめ記事