Dnaiel
Dnaiel

Reputation: 7832

linux command to remove a column, add id column and add another extra column unix/linux awk

I have a tab delimited file, I'd like to re-format it and delete the original, all into one line.

It is a tab-delimited file, I'd like for example to:

remove a given column (i.e., column 3), add another id column in the middle (i.e., btw columns 1 and 2) where each line is an id (e.g. row1 is id1, row2 is id2, etc...), and then add another column at the end with text (i.e., text where each row is hello).

All changes in one line, and finally delete the original file, and the new file with the same as the original.

Example:

fnamein.txt

rogelio\tdelgado\t3453434\tlas encinas\n
mario\tmoreno\t4563432\tcasinos\n
etc...


fname.out

rogelio\tid1\tdelgado\t3453434\tlas encinas\taddress\n
mario\tid2\tmoreno\t4563432\tcasinos\taddress\n
etc...

(as you can see i added id column btw col 1 and 2, and address column (always same word) at the end).

Just wondering is there is an easy way to do that in linux, i am new to the power of linux commands.

Thanks!

Upvotes: 1

Views: 3446

Answers (3)

Dnaiel
Dnaiel

Reputation: 7832

Well, unixrules answered helped me to answer the entire question:

awk -F'\t' 'BEGIN {OFS = FS} {id++}{print $1,"id"id,$2,$3,$4,"address"}' filein.txt > test.tmp && mv test.tmp filein.txt.

These answer does exactly what I intended to do originally.

Thanks all for your help.

Upvotes: 1

unixrules
unixrules

Reputation: 608

Another way is to use awk

awk -F'\t'  '{print $1, $2, $3}'   filename

where -F is the field separator. awk will separate the file into the respective fields and all you need to do is to print the fields. $1 is first field etc. To skip a field, omit it.

awk '{print $1, $3}'  filename

will only print the first and the third fields.

Upvotes: 2

ruakh
ruakh

Reputation: 183251

One way:

perl -i -pwe 's/^([^\t*])\t([^\t*])\t[^\t*]\t(.*)/$1\tid$.\t$2\t$3\taddress/;' FILENAME

Upvotes: 1

Related Questions