Home > Software design >  How can I add a column in the 4th position in a txt file using sed, awk?
How can I add a column in the 4th position in a txt file using sed, awk?

Time:08-12

I've got a txt file with this content:

   name    space   valid   date1        date2 
    abc     mon     yes    2022-10-10   2022-10-10
    def     tue     yes    2022-10-10   2022-10-10
    ghi     wed     yes    2022-10-10   2022-10-10
    jkl     thu     yes    2022-10-10   2022-10-10

I need to add a column in the fourth position of the file with a header "location" and content as shown below.

   name    space   valid   location     date1        date2 
    abc     mon     yes    newyork    2022-10-10   2022-10-10
    def     tue     yes    newyork    2022-10-10   2022-10-10
    ghi     wed     yes    newyork    2022-10-10   2022-10-10
    jkl     thu     yes    newyork    2022-10-10   2022-10-10

Is there any way to do it using one the Linux commands like sed, awk?

I tried this but it didn't work:

awk 'BEGIN {FS=OFS=","} NR==1{$0="name, space, valid, location, date1, date2"} NR>1{$3=sprintf("\t,%s",$3)}1' values.txt

Any help would be much appreciated.Thank you!

CodePudding user response:

You may use this awk solution:

awk 'BEGIN {FS=OFS="\t"}
{$3 = $3 OFS (NR == 1 ? "location" : "newyork")} 1' file

name  space  valid  location  date1       date2
abc   mon    yes    newyork   2022-10-10  2022-10-10
def   tue    yes    newyork   2022-10-10  2022-10-10
ghi   wed    yes    newyork   2022-10-10  2022-10-10
jkl   thu    yes    newyork   2022-10-10  2022-10-10
  • Related