Display all fields except the last

纵然是瞬间 提交于 2019-12-01 16:01:28

Both these sed and awk solutions work independent of the number of fields.

Using sed:

$ sed -r 's/(.*)\..*/\1/' file
1.2.3.4
sanma.nam
c.d.b

Note: -r is the flag for extended regexp, it could be -E so check with man sed. If your version of sed doesn't have a flag for this then just escape the brackets:

sed 's/\(.*\)\..*/\1/' file
1.2.3.4
sanma.nam
c.d.b

The sed solution is doing a greedy match up to the last . and capturing everything before it, it replaces the whole line with only the matched part (n-1 fields). Use the -i option if you want the changes to be stored back to the files.

Using awk:

$ awk 'BEGIN{FS=OFS="."}{NF--; print}' file
1.2.3.4
sanma.nam
c.d.b

The awk solution just simply prints n-1 fields, to store the changes back to the file use redirection:

$ awk 'BEGIN{FS=OFS="."}{NF--; print}' file > tmp && mv tmp file

Reverse, cut, reverse back.

rev file | cut -d. -f2- | rev >newfile

Or, replace from last dot to end with nothing:

sed 's/\.[^.]*$//' file >newfile

The regex [^.] matches one character which is not dot (or newline). You need to exclude the dot because the repetition operator * is "greedy"; it will select the leftmost, longest possible match.

With cut on the reversed string

cat youFile | rev |cut -d "." -f 2- | rev

If you want to keep the "." use below:

awk '{gsub(/[^\.]*$/,"");print}' your_file
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!