Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print all but select fields in awk

Tags:

bash

awk

I have a large file with hundreds of columns that I want to remove only the third and fourth columns from and print the rest to a file. My initial idea was to make an awk script like awk '{print $1, $2, for (i=$5; i <= NF; i++) print $i }' file > outfile. However, this code does not work.

I then tried:

awk '{for(i = 1; i<=NF; i++)
if(i == 3 || i == 4) continue
else
print($i)}' file > outfile

But this just printed everything out in one field. It would be possible to split this up into two scripts and combine them with unix paste but this seems like something that should be able to be done in one line.

like image 792
Stedy Avatar asked Jun 23 '11 17:06

Stedy


3 Answers

Your first try was pretty close. Modifying it to use printf and including the field separators worked for me:

awk '{printf $1FS$2; for (i=5; i <= NF; i++) printf FS$i; print NL }'
like image 187
Carl Norum Avatar answered Oct 20 '22 17:10

Carl Norum


What about something like:

cat SOURCEFILE | cut -f1-2,5- >> DESTFILE

It prints the first two columns, skips the 3rd and 4rth, and then prints from 5 onwards to the end.

like image 31
thomascirca Avatar answered Oct 20 '22 18:10

thomascirca


How about just setting the third and fourth columns to an empty string:

echo 1 2 3 4 5 6 7 8 9 10 |
awk -F" " '{ $3="";  $4=""; print}'
like image 35
jim Avatar answered Oct 20 '22 18:10

jim