从shell中的每一行中提取最后一个单词[duplicate]

时间:2022-09-13 14:22:19

This question already has an answer here:

这个问题在这里已有答案:

i have file result.txt which look like this:

我有文件result.txt,如下所示:

acb.xyz.asd
mnt.x.sdr
s.ere.43

I want to write shell script which will extract the last word and print like below:

我想编写shell脚本,它将提取最后一个单词并打印如下:

asd
sdr
43

I tried awk command but it didn't work:

我试过awk命令,但它不起作用:

awk 'NF>1{print $NF}' result.txt

I think i need to use delimiter "." and then parse the result.txt based on parse result. Plz help.

我想我需要使用分隔符“。”然后根据解析结果解析result.txt。 Plz的帮助。

3 个解决方案

#1


I usually use rev | cut | rev to extract the columns from the right.

我通常使用rev |切| rev从右侧提取列。

 rev result.txt | cut -d. -f1 | rev

#2


You were indeed missing the -F option with awk

你确实错过了awk的-F选项

awk -F. 'NF>1{print $NF}' result.txt

Alternatively, you can use cut and specify both the delimiter and field that you want

或者,您可以使用剪切并指定所需的分隔符和字段

cut -d. -f3 result.txt

#3


I think sed -r -e 's/[^.]+\.[^.]+.//' will do what you want.

我认为sed -r -e's / [^。] +。[^。] +。//'会做你想要的。

#1


I usually use rev | cut | rev to extract the columns from the right.

我通常使用rev |切| rev从右侧提取列。

 rev result.txt | cut -d. -f1 | rev

#2


You were indeed missing the -F option with awk

你确实错过了awk的-F选项

awk -F. 'NF>1{print $NF}' result.txt

Alternatively, you can use cut and specify both the delimiter and field that you want

或者,您可以使用剪切并指定所需的分隔符和字段

cut -d. -f3 result.txt

#3


I think sed -r -e 's/[^.]+\.[^.]+.//' will do what you want.

我认为sed -r -e's / [^。] +。[^。] +。//'会做你想要的。