Home > database >  How to add a Header with value after a perticular column in linux
How to add a Header with value after a perticular column in linux

Time:08-24

Here I want to add a column with header name Gender after column name Age with value.

cat Person.csv

First_Name|Last_Name||Age|Address
Ram|Singh|18|Punjab
Sanjeev|Kumar|32|Mumbai

I am using this:

cat Person.csv | sed '1s/$/|Gender/; 2,$s/$/|Male/' 

output:

First_Name|Last_Name||Age|Address|Gender
Ram|Singh|18|Punjab|Male
Sanjeev|Kumar|32|Mumbai|Male

I want output like this:

First_Name|Last_Name|Age|Gender|Address
Ram|Singh|18|Male|Punjab
Sanjeev|Kumar|32|Male|Mumbai

CodePudding user response:

I took the second pipe out (for consistency's sake) ... the sed should look like this:

$ sed -E '1s/^([^|] \|[^|] \|[^|] \|)/\1Gender|/;2,$s/^([^|] \|[^|] \|[^|] \|)/\1male|/' Person.csv
First_Name|Last_Name|Age|Gender|Address
Ram|Singh|18|male|Punjab
Sanjeev|Kumar|32|male|Mumbai

We match and remember the first three fields and replace them with themselves, followed by Gender and male respectively.

CodePudding user response:

Using awk:

$ awk -F"|" 'BEGIN{ OFS="|"}{ last=$NF; $NF=""; print (NR==1) ? $0"Gender|"last : $0"Male|"last }' Person.csv
First_Name|Last_Name||Age|Gender|Address
Ram|Singh|18|Male|Punjab
Sanjeev|Kumar|32|Male|Mumbai

Use '|' as the input field separator and set the output field separator as '|'. Store the last column value in variable named last and then remove the last column $NF="". Then print the appropriate output based on whether is first row or succeeding rows.

  • Related