當所需的子字串位于每行的末尾時,如何從檔案的每一行中捕獲特定的子字串。
代碼
sed 's/.*\(by user [0-9a-zA-Z]*\).*/\1/p' file > output
$cat file
2021-04-02 [Information] read first line from file - Reviewing by user skha12
2022-04-29 09:45:14,754 [1426] [Information] This is a single line
2021-04-02 [debugging] read first line from file - Reviewing by user nar73h
2021-04-02 [Information] read first line from file - Editing by user abcxxs
2022-04-29 09:45:14,754 [1426] [Information] This is a single line
2021-04-02 [debugging] read first line from file - Reviewing by user Y54321
2022-04-29 08:49:12,554 [143] [debugging] This is a single line
2022-04-29 09:40:13,852 [5] [Information] This is a single line
2022-04-29 09:45:14,754 [1426] [Information] This is a single line
預期產出
nar73h
skha12
abcxxs
Y54321
uj5u.com熱心網友回復:
使用awk
$ awk '{print $NF}' input_file
skha12
nar73h
abcxxs
Y54321
使用sed
$ sed 's/.* //' input_-file
skha12
nar73h
abcxxs
Y54321
uj5u.com熱心網友回復:
grep:
<file grep 'by user' | grep -o '[^ ]\ $'
切:
<file grep 'by user' | rev | cut -d' ' -f1 | rev
賽德:
<file sed -n '/by user/ s/.* //p'
uj5u.com熱心網友回復:
$ awk '/by user/{print $NF}' file
skha12
nar73h
abcxxs
Y54321
$ sed -n 's/.*by user //p' file
skha12
nar73h
abcxxs
Y54321
uj5u.com熱心網友回復:
如果要使用gnu grep,并且所需的子字串位于每行的末尾:
grep -oP ".*\bby\h user\h \K[0-9a-zA-Z] $" file > output
解釋
.*匹配整行\bby\h user\h一個單詞邊界,然后匹配by user1個或多個空格\K清除當前匹配緩沖區(忘記到目前為止匹配的內容)[0-9a-zA-Z]匹配字符類中任何范圍的 1 次以上$字串結束
檔案輸出包含:
skha12
nar73h
abcxxs
Y54321
uj5u.com熱心網友回復:
這是我用來使用 grep 獲得預期輸出的命令 -
grep "by user" file | awk '{print $NF}' > output
uj5u.com熱心網友回復:
perl -alnE'say $F[-1] if /by user/' file
grep -oP '(?<=by user ).*' file
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/471522.html
