2つの変数を使用して単一のテキストファイルを構成します。

2つの変数を使用して単一のテキストファイルを構成します。

次の内容でテキストファイルを作成しようとしています。

user name is ${name}
and his mobile number is ${number}

ユーザーが10人で携帯電話番号が10個あります。ユーザー名はに保存され、user.txt連絡先番号はに保存されますcontact.txt

user.txt次のようになります。

apple
cat
tom

contact.txt次のように、

1234
3456
5678

私の出力は次のとおりです。

user name is apple
and his mobile number is 1234

user name is cat
and his mobile number is 3456

user name is tom
and his mobile number is 5678

この出力を単一のファイルにしたい。誰かがシェルとPythonスクリプトを助けることができますか?

ベストアンサー1

これは、標準シェルの組み込みおよび一般的なツールを使用して行うことができます。

paste -d'|' user.txt contact.txt | while IFS='|' read user contact ; do
  printf "user name is %s\nand their mobile is %s\n" "${user}" "${contact}"
done

入力リダイレクトにしばしば好まれるbashismを使ったわずかなリミックスです。

while IFS='|' read user contact ; do
  printf "user name is %s\nand their mobile is %s\n" "${user}" "${contact}"
done < <(paste -d"|" user.txt contact.txt)

> "somefilename.txt"コマンドの最後の行に追加すると、出力全体を選択したファイルにリダイレクトできます。

おすすめ記事