IP awkの最後のオクテットの変更

IP awkの最後のオクテットの変更

次のファイルがあるとします。

Somestring 1.2.3.4 more charachters and strings
Somestring 1.2.3.5 more charachters and strings
Somestring 1.2.3.6 more charachters and strings

IPの最後のオクテットを変更したいです。

Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings

awkやsedでどのようにこれを達成できますか?

私がしたことは次のとおりです。

awk '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/); ip = substr($0,RSTART,RLENGTH-1); print ip }' file  

しかし、これは単にIPを印刷するだけで、完全に正確ではありません。

また、以下を試しました。

awk '{split($2,ip,".") gsub(ip[2],"x"); print}' 

しかし、これも最初のオクテットを置き換えるので、正しくありません。

Somestring x.2.3.x more charachters and strings
Somestring x.2.3.x more charachters and strings
Somestring x.2.3.x more charachters and strings

助けてくれてありがとう

ベストアンサー1

この目的のためにsed

$ sed -E 's/ (([0-9]{1,3}\.){3})[0-9]{1,3} / \1x /' file
Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings
Somestring 1.2.3.x more charachters and strings

[0-9]{1,3}\.これは、スペースの後に3つのグループ(1〜3桁の数字の後にドットがあります)を見つけてキャプチャします。その後、最後のグループと最後のスペース\1も変更されます。これはすべて、3つの数字と点を持つ最初のセットがある場所[0-9]{1,3}に置き換えられます。␣\1x␣\1

おすすめ記事