2

I have bash script looping through several files in a directory. The file identifier has been saved as a variable $num. What I would like to do is add $num as another column in my data like in the example below:

ORIGINAL INPUT:

A B C D E
2 79 56 SD L
1 09 67 JK S
9 60 37 KD G
0 10 47 SO E

EXPECTED OUTPUT:

A B C D E id
2 79 56 SD L 1
1 09 67 JK S 1
9 60 37 KD G 1
0 10 47 SO E 1

*in above example, $num = 1

Ultimately, I want to take a subset of lines from each looped file and cat them into a single large file. For me to know which file the line came from, I need the id from $num.

I have tried using awk '{$12 = $num}' filename but this does not work at all.

Please help!

1

try (awk can be in one line)

 id=...
 awk -v id=$id 'NR==1 { x=NF+1 ; $x = "id" ; print ; }
                NR > 1 { x=NF+1 ; $x = id ; print ; } ' file > new_file

where

  • -v id=$id paste id from shell to awk, if id has funny char, use -v id="îd"
  • NR == 1 , NR > 1 select first, other line
  • { x=NF+1 ; $x = id ; print ; } push $id ( id in awk )
  • Works perfectly! – Bob Oct 26 '15 at 15:52
0

The following sed script assumes that the field separator is a space. If it's a tab, change the space in both s/// sed commands to \t.

The first line has id appended, second and subsequnt lines have $num appended.

$ num=1
$ sed -e "1 s/$/ id/ ; 2,$ s/$/ $num/" input.txt 
A B C D E id
2 79 56 SD L 1
1 09 67 JK S 1
9 60 37 KD G 1
0 10 47 SO E 1

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.