I have a text file with 6 columns. How can I delete the last three columns from this file?
c1 c2 c3 c4 c5 c6
desired output
c1 c2 c3
I have a text file with 6 columns. How can I delete the last three columns from this file?
c1 c2 c3 c4 c5 c6
desired output
c1 c2 c3
If spacing are not important, here is how to delete last 3 fields.
You could even use
But its not as robust as the first example.
To delete the last
N
columns in each row, you can simply reduceNF
(the number of fields) by that amount, taking into account the special case where there aren't enough columns to delete):Keep in mind that
awk
is primarily a tool for processing columns of data. You'll notice that my output has a single space between fields since column-based processing doesn't usually care about the type of whitespace.If spacing is important (ie, you want to preserve, for example, the number of spaces between columns), you should probably look into another tool.
awk '{print $1 " " $2 " " $3}' filename > filename.new
You can use @paxdiablo's
awk
to reduce the value ofNF
alternatively you can use
sed
If you are on Linux, GNU
sed
provides-r
Pure bash (if spacing is not important):
use
cut -d' ' -f5-
if there are trailing space(s), or trim trailing spaces before these.But I do like the Jotne/paxdiablo's awk NF solution much better.
If columns are separated by single space:
If columns are separated by multiple space:
If columns are separated by tab: