0

How can I add a new column to a tab delimited file, at the end of the file, containing the same values for each row.

For example:

infile.txt

Name    Age Address Sex
X   12  adrs1   M
Y   15  adrs2   F
Z   10  adrs3   M

I want to add another coloumn 'School' containing same values'st.xaviers ' for each row

outfile.txt

Name    Age Address Sex School
X   12  adrs1   M   st.xaviers  
Y   15  adrs2   F   st.xaviers
Z   10  adrs3   M   st.xaviers

I have tried awk '{print $0, "School"} to add the column. How can I add the 'st.xaviers' to each row in column "School" ?

Now, if this is part of shell script, and I have a predefined variable School=st.xaviers.

How Can I add $School values to the Column 'School' in outfile.txt

0

I swear the very same question was asked and answered a couple of weeks ago... but I can't find it.

The recipe is:

  • check if the first column is "Name", and print the line a TAB and "School" when it is; done, skip to the next line
  • all the othern, non-empty lines ($1 exists) must be printed with a following TAB and "st.xaviers"

Such as:

awk -vschool="$School" '$1=="Name" { print $0 "\tSchool"; next}; $1 {print $0 "\t" school}'

or

export School
awk '$1=="Name" { print $0 "\tSchool"; next}; $1 {print $0 "\t" ENVIRON["School"]}'

The former one defines an awk variable using -v, the latter peeks into its environment after export allows it to see School.

  • Thanks a lot. It worked. How can include the {print $0 "\tst.xaviers"}' argument from $school within a shell script, example: l#!/usr/bin/bash infile=infile.txt outfile=outfile.txt school=st.xaviers #I do some extra operations with the files #and finally would like to awk '$1=="Name" { print $0 "\tSchool"; next}; $1 {print $0 "\tst.xaviers"}' $infile $outfile – panbar Mar 17 '16 at 14:58
  • I get it, so you want school to be dynamic. Answer edited. – Gombai Sándor Mar 17 '16 at 15:07
0

If you allow Perl as a superset of awk:

perl -p -i -e 's/Sex$/Sex\tSchool/ or s/$/\tst.xaviers/'

I imagine a similar construction is possible in awk (or sed) too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.