awkを使用して他の列を検索して置換する

awkを使用して他の列を検索して置換する

ファイルを変更しようとしています。

値を見つけて他の列の別の値に置き換えるために使用しますawk

入力する( UiO-66Zr-EH.mof):

unit ntype qqatom
  1  'Zr1'  0.0d0
vibration
0
improper
0
unit ntype qqatom
  2  'H1'  0.0d0
vibration
0
improper
0
unit ntype qqatom
  3  'C25'  0.0d0
vibration
0
improper
0
unit ntype qqatom
  4  'O1'  0.0d0

出力( output):

unit ntype qqatom
  1  'Zr1'  2.222d0
vibration
0
improper
0
unit ntype qqatom
  2  'H1'  3.333d0
vibration
0
improper
0
unit ntype qqatom
  3  'C25'  7.456d0
vibration
0
improper
0
unit ntype qqatom
  4  'O1'  9.99d0

私は次のコマンドを試しました。

awk < UiO-66Zr-EH.mof '$2 ~ /Zr1/ {$3 ="2.222.d0"}1''$2 ~ /O1/ {$3 ="9.99d0"}1''$2 ~ /C25/ {$3 ="7.45d0"}1''$2 ~ /H1/ {$3 ="3.333d0"}1' > output

しかし、それはうまく動作しません。

awk同じフォーメーションを維持しながらこれを実行するために使用できるものはありますか?

ベストアンサー1

おそらく、2番目の列で正規表現の一致ではなく文字列比較を実行したいと思うでしょう。提供された例を使用してこれを行うには、比較に一重引用符を含める必要があります。これはすべてをシェル引用悪夢にします。これを行うと、次のような結果が得られます。

awk "\$2==\"'Zr1'\" { \$3=\"2.222.d0\" }
     \$2==\"'O1'\" { \$3=\"9.99d0\" }
     \$2==\"'C25'\" { \$3 =\"7.45d0\" }
     \$2==\"'H1'\" { \$3 =\"3.333d0\" }
     { print }" <UiO-66Zr-EH.mof

おすすめ記事