Home > Software design >  Add certain strings to the front of given lines
Add certain strings to the front of given lines

Time:07-30

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!

CodePudding user response:

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 creating unnecessary array elements:

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

CodePudding user response:

mawk 'FNR<NR? $!_=__[FNR] $_: (__[ $_]=$NF)<_' FS='. ,' f2 f1
efgdx
abcdefgfx
aa
efgefgdx
hijb
efgdx

CodePudding user response:

cp file1 file1.bak 
while IFS="," read -r line_no string; do
    sed -i "${line_no}s/^/$string/" file1 
done < file2
$ cat file1
efgdx
abcdefgfx
aa
efgefgdx
hijb
efgdx
  • Related