Display all fields except the last Display all fields except the last shell shell

Display all fields except the last


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

Using sed:

$ sed -r 's/(.*)\..*/\1/' file1.2.3.4sanma.namc.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/' file1.2.3.4sanma.namc.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}' file1.2.3.4sanma.namc.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