Display all fields except the last

user1745857 picture user1745857 · Dec 13, 2012 · Viewed 13.8k times · Source

I have a file as show below

1.2.3.4.ask
sanma.nam.sam
c.d.b.test

I want to remove the last field from each line, the delimiter is . and the number of fields are not constant.

Can anybody help me with an awk or sed to find out the solution. I can't use perl here.

Answer

Chris Seymour picture Chris Seymour · Dec 13, 2012

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