Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add column to middle of tab-delimited file (sed/awk/whatever)

Tags:

sed

awk

I'm trying to add a column (with the content '0') to the middle of a pre-existing tab-delimited text file. I imagine sed or awk will do what I want. I've seen various solutions online that do approximately this but they're not explained simply enough for me to modify!

I currently have this content:

Affx-11749850   1       555296  CC

I need this content

Affx-11749850   1   0   555296  CC

Using the command awk '{$3=0}1' filename messes up my formatting AND replaces column 3 with a 0, rather than adding a third column with a 0.

Any help (with explanation!) so I can solve this problem, and future similar problems, much appreciated.

like image 845
Charley Farley Avatar asked Aug 14 '12 10:08

Charley Farley


2 Answers

Using the implicit { print } rule and appending the 0 to the second column:

awk '$2 = $2 FS "0"' file

Or with sed, assuming single space delimiters:

sed 's/ / 0 /2' file

Or perl:

perl -lane '$, = " "; $F[1] .= " 0"; print @F'
like image 119
Thor Avatar answered Nov 10 '22 09:11

Thor


awk '{$2=$2" "0; print }' your_file

tested below:

> echo "Affx-11749850 1 555296 CC"|awk '{$2=$2" "0;print}'
Affx-11749850 1 0 555296 CC
like image 31
Vijay Avatar answered Nov 10 '22 10:11

Vijay