#2 awkの勉強

  linux command  [公開]
icon c012vu5 が 2021/04/19 5:52 に投稿 ( icon c012vu5 が 2021/04/19 6:50 に編集 <更新履歴> )

基本的な文字列置換の方法が紹介してあります。
パターンマッチで複数の該当行が出て来た場合に、どの行で置換を行うのか指定する、というのが目標でした。
一番下にコマンドが書いてあります。

また、sedでの書き方、修正、改善などありましたらコメントお願いします。

入力

$ cat test.txt
hoge hoge hoge
hoge hoge hoge MARK
hoge hoge hoge

全置換

$ sed -i test.txt -e 's/hoge/fuga/g'
$ awk -i inplace '{ gsub("hoge", "fuga"); print }' test.txt
$ cat test.txt
fuga fuga fuga
fuga fuga fuga MARK
fuga fuga fuga

列指定置換

各行で1番目に一致した文字列を置換

$ sed -i test.txt -e 's/hoge/fuga/'
$ sed -i test.txt -e 's/hoge/fuga/1'
$ awk -i inplace '{ sub("hoge", "fuga", $1); print }' test.txt
$ cat test.txt
fuga hoge hoge
fuga hoge hoge MARK
fuga hoge hoge

行指定置換

1行目の各列で一致した文字列を置換

$ sed -i test.txt -e '1 s/hoge/fuga/g'
$ awk -i inplace '{ if(NR==1){ gsub("hoge", "fuga")}; print }' test.txt
$ cat test.txt
fuga fuga fuga
hoge hoge hoge MARK
hoge hoge hoge

行列指定置換

2行2列目の文字列が一致したら置換

$ awk -i inplace '{ if(NR==2){ sub("hoge", "fuga", $2) }; print $0 }' test.txt
$ cat test.txt
hoge hoge hoge
hoge fuga hoge MARK
hoge hoge hoge

パターンマッチ

検索文字列に一致した各行で1番目に一致した文字列を置換

$ sed -i test.txt -e '/MARK/s/hoge/fuga/'
$ awk -i inplace '{ if($0 ~ "MARK"){ sub("hoge", "fuga") }; print }' test.txt
$ cat test.txt
hoge hoge hoge
fuga hoge hoge MARK
hoge hoge hoge

検索文字列に一致した行のうち、1番目の行で一致した文字列を置換

入力

$ cat longtest.txt
hoge hoge hoge hoge hoge
hoge hoge hoge hoge hoge MARK
hoge hoge hoge hoge hoge
hoge hoge hoge hoge hoge MARK
hoge hoge hoge hoge hoge

コマンド

if(c==$NUM)$NUMでパターンマッチした内の何行目を対象に置換するのか決めている

$ sed -i longtest.txt -e /わからない/
$ awk -i inplace '/MARK/{ c++; if(c==1){ sub("hoge","fuga") }} 1' longtest.txt
$ cat longtest.txt
hoge hoge hoge hoge hoge
fuga hoge hoge hoge hoge MARK
hoge hoge hoge hoge hoge
hoge hoge hoge hoge hoge MARK
hoge hoge hoge hoge hoge

 添付ファイル     - [0]


 コメント追加