sed 仅删除行尾的最后一个空格,与 awk 结合

sed 仅删除行尾的最后一个空格,与 awk 结合

我有那些线

Siouxsie Sioux  Siouxsie Sioux  ...     
Sylvia Tobias   Sylvia Tobias   ...     
Sydney Urshan   Sydney Urshan   ... 
Club Drummer (uncredited)   Club Drummer (uncredited)   ...

使用 awk,我打印分隔的第一列选项卡,然后添加一个,

awk -F "\t" '{print $1","}'

没问题,但我看到末尾有空格,所以我使用 sed

awk -F "\t" '{print $1","}'|sed -r 's/(^[^[:blank:]]+[[:blank:]]+[^[:blank:]]+)[[:blank:]]+/\1/'

这样就可以了,但还要删除第二个空白,所以

Club Drummer (uncredited) ,

变得

Club Drummer(uncredited),

我想

Club Drummer (uncredited),

那么如何只删除最后一个空格呢?谢谢

答案1

awk -F ' *\t' '{print $1 ","}'

或者:

sed $'s/ *\t.*/,/'

答案2

awk使用自身去除那些尾随空格

awk -F'\t' '{sub(/[[:blank:]]+$/, "", $1);print $1","}' file

答案3

您可以使用printf而不是使用print来解决这个问题。

$ awk '{for (i=1;i<NF;i++)printf("%s ", $i);printf("\b%s\n",",")}' file.txt 
Siouxsie Sioux Siouxsie Sioux,
Sylvia Tobias Sylvia Tobias,
Sydney Urshan Sydney Urshan,
Club Drummer (uncredited) Club Drummer (uncredited),

或者如果你需要它sed

$ sed -re 's/ +\.\.+/,/g' file.txt 
Siouxsie Sioux  Siouxsie Sioux,     
Sylvia Tobias   Sylvia Tobias,     
Sydney Urshan   Sydney Urshan, 
Club Drummer (uncredited)   Club Drummer (uncredited),

答案4

我认为整个操作可以使用sed 's/^\([^\t]*\).*/\1,/'...来完成

相关内容