How to exclude last N columns in Bash on Linux?

How to exclude last N columns of a string in bash? The point is that the number of columns in each line is uncertain (but > N).

For example, I would like to remove the last 2 columns separated by '.' in the following lines.

systemd.3.gz
systemd.mount.3.gz
systemd.mount.f.3.gz

The simple cut command

cut -d'.' -f1

only works for the 1st line and will fail for the last 2 lines.

How to exclude last N columns in Bash on Linux?

asked Mar 27, 2015 by olivie (510 points)

1 Answer

 
Best answer

I provide 2 method here, one using cut plus rev and another one use awk.

Exclude last 2 columns using cut and rev

Used together with rev, cut needs not to know the number of columns in a line.

rev | cut -d '.' -f3- | rev

Example,

$ cat /tmp/test.txt \
| rev | cut -d '.' -f3- | rev
systemd
systemd.mount
systemd.mount.f

Exclude last 2 columns using awk

awk -F. '{for(i=0;++i<=NF-3;) printf $i"."; print $(NF-2)}' 

Example,

$ cat /tmp/test.txt \
| awk -F. '{for(i=0;++i<=NF-3;) printf $i"."; print $(NF-2)}' 
systemd
systemd.mount
systemd.mount.f
answered Mar 27, 2015 by Eric Z Ma (42,250 points)
selected Mar 27, 2015 by olivie

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...