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?

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 by Eric Z Ma.

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *