2

I have two input files:

input1 is the file I need to process, input1 file example:

efgdx
efgfx
aa
efgdx
b
efgdx

input2 file tells what characters need to be add to which line, for example:

2,abcd
4,efg
5,hij

So, "abcd" should be added to the front of 2nd line, "efg" should be added to the front of 4th line, ...

This is the output I want:

efgdx
abcdefgfx
aa
efgefgdx
hijb
efgdx     

I tried the following code but it will add strings to every line

awk '!p { getline m < "input2"; split(m, a, ","); p = 1} NR == a[1] {p=0} 1 { print a[2] $0}' input1

output from above code:

abcdefgdx
abcdefgfx
efgaa
efgefgdx
hijb
hijefgdx

Thanks very much for your inputs!

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
Wen Wang
  • 21
  • 3

2 Answers2

3

This awk one-liner should do the job

awk -F, 'NR==FNR{ a[$1]=$2; next } { print a[FNR] $0 }' input2 input1

or, a better method, suggested by Ed Morton, which avoids wasting memory inside awk by creating unnecessary array elements:

awk -F, 'NR==FNR{ a[$1]=$2; next } FNR in a{ $0=a[FNR]$0 } 1' input2 input1
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
1
mawk 'FNR<NR? $!_=__[FNR] $_: (__[+$_]=$NF)<_' FS='.+,' f2 f1
efgdx
abcdefgfx
aa
efgefgdx
hijb
efgdx
RARE Kpop Manifesto
  • 2,453
  • 3
  • 11