Search code examples
sedawk

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


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.


Solution

  • 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'