Text-Processing

awk 按字元分割參數

  • April 5, 2022

文件是:

BASH.NIR
SH.ABI

我希望 awk 腳本顯示:

User is NIR, SHELL is BASH
User is ABI, SHELL is SH

我不知道如何按字元拆分參數。這個想法是:

cat file.txt | awk '{print "User is " afterDot($1) ", SHELL is " beforeDot($1)}'

您可以使用中的字元串函式awk

$ (echo BASH.NIR; echo SH.ABI FOOBAR) | awk '{p=index($1,".");print "User is", substr($1,p+1) ", SHELL IS", substr($1,0,p-1)}'
User is NIR, SHELL IS BASH
User is ABI, SHELL IS SH

index函式返回要找到的字元的位置(在本例中為點)substr並將返回一個子字元串。我們使用p+1p-1不包括點。

有關更多資訊,請查看手冊頁的“字元串函式”部分awk

您可以只.用作欄位分隔符:

awk -F. '{ print "User is " $2 ", SHELL is " $1 }' file.txt

引用自:https://unix.stackexchange.com/questions/106243