How to exclude last N columns in Bash on Linux?
Posted on In QAHow 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