WestCoastProjects
WestCoastProjects

Reputation: 63281

Remove first columns then leave remaining line untouched in awk

I am trying to use awk to remove first three fields in a text file. Removing the first three fields is easy. But the rest of the line gets messed up by awk: the delimiters are changed from tab to space

Here is what I have tried:

head pivot.threeb.tsv | awk 'BEGIN {IFS="\t"} {$1=$2=$3=""; print }' 

The first three columns are properly removed. The Problem is the output ends up with the tabs between columns $4 $5 $6 etc converted to spaces.

Update: The other question for which this was marked as duplicate was created later than this one : look at the dates.

Upvotes: 7

Views: 10229

Answers (4)

Bobo
Bobo

Reputation: 9163

awk '{for (i=4; i<NF; i++) printf $i " "; print $NF}'

Upvotes: 0

anubhava
anubhava

Reputation: 786359

Actually this can be done in a very simple cut command like this:

cut -f4- inFile

Upvotes: 6

Kent
Kent

Reputation: 195289

first as ED commented, you have to use FS as field separator in awk. tab becomes space in your output, because you didn't define OFS.

awk 'BEGIN{FS=OFS="\t"}{$1=$2=$3="";print}' file

this will remove the first 3 fields, and leave rest text "untouched"( you will see the leading 3 tabs). also in output the <tab> would be kept.

awk 'BEGIN{FS=OFS="\t"}{print $4,$5,$6}' file

will output without leading spaces/tabs. but If you have 500 columns you have to do it in a loop, or use sub function or consider other tools, cut, for example.

Upvotes: 6

Chris Seymour
Chris Seymour

Reputation: 85913

If you don't want the field separation altered then use sed to remove the first 3 columns instead:

sed -r 's/(\S+\s+){3}//' file

To store the changes back to the file you can use the -i option:

sed -ri 's/(\S+\s+){3}//' file

Upvotes: 3

Related Questions