假设我有一个输入文件如下:
的Oracle
ORAC
Orac10
SYS
系统管理员
ABC
ABCA
BBBB
我的输出应转换为以下内容:
甲骨文,ORAC,Orac10
SYS,系统管理员
ABC,ABCA
BBBB
答案 0 :(得分:0)
使用awk:
awk '{key=substr($0,1,3)} key!=pkey{if (NR>1) print s; s=$0; pkey=key;next}
{s=s "," $0} END{print s}' file
Oracle,Orac,Orac10
Sys,Sysadmin
abc,abca
bbbb
<强>解释强>
key=substr($0,1,3) # extract first 3 chars of each line and store in variable key
key!=pkey { # if previous key (pkey) is != current key then execute
if (NR>1) print s # for record>1 print aggregated string s
s=$0 # reset s by storing current line in variable s
pkey=key # store current key in a variable pkey
next # move to next line
} # end of key!=pkey block
{s=s "," $0} # append current line in var s after a comma
END{print s} # print s last time