我有这个输入文本文件:
Pedro Paulo da Silva
22 years old
Brazil
Bruce Mackenzie
30 years old
United States of America
Lee Dong In
26 years old
South Korea
Run Code Online (Sandbox Code Playgroud)
人名始终是文件的第一行(以及空行 /n 之后的第一行)。
我必须执行此输出(忽略除第一行中的名称之外的所有内容):
PedroPdS
BruceM
LeeDI
Run Code Online (Sandbox Code Playgroud)
不知道如何用 awk 做到这一点。我只知道 awk 'print {$number}' 将获取列 $number ,这就是我应该如何获取他们的名字。
我在这里搜索并找到了这个:sed -e 's/$/ /' -e 's/\([^ ]\)[^ ]* /\1/g' -e 's/^ *//'
但我必须使用 awk。
请您尝试以下操作:
awk -v RS="" -F '\n' ' # records are separated on blank lines by setting RS to null
{
n = split($1, b, " ") # split the name on spaces
init = b[1] # the first name
for (i = 2; i <= n; i++) # loop over the remaining
init = init substr(b[i], 1, 1) # append the initial
print init
}' input.txt
Run Code Online (Sandbox Code Playgroud)
输出:
PedroPdS
BruceM
LeeDI
Run Code Online (Sandbox Code Playgroud)