zwlayer zwlayer - 1 year ago 113
Linux Question

How to replace some of the lines of file A according to line numbers in file B

I have two file File A and File B.

Lines in File A consist of either two fields seperated with a tab or single field. In File B each line consist of 3 fields (Again seperated with tabs) The first field is an integer, the second and third fields are some string. Now, I want to change a line in File A if its line number is seen in File B (at the first field). By changing, I mean I want to merge the second and third fields on that line in file B by tab and put the corresponding line in File A

For example, Let's say I have a File A containing 3 Lines

File A:
poo foo
koo goo
too roo


And I have a file with 2 lines.

File B:
2 change-second-line with-this
3 change-third-line with-that


At the end, I want a file with the following content:

File final:
poo foo
change-second-line with-this
change-third-line with-that


Is there a way to do that ? Generally, while asking question I also put a code snippet that shows my effort but this time I couldn't even start to write to do that.

Answer Source
awk 'FNR==NR{arr[$1]=substr($0,index($0,$2));next}
     FNR in arr{print arr[FNR];next}1
    ' fileB fileA

OR

awk 'FNR==NR{arr[$1]=substr($0,length($1)+2);next}
     FNR in arr{print arr[FNR];next}1
    ' fileB fileA

Test Results:

$ cat fileA
poo    foo
koo    goo
too    roo  

$ cat fileB
2 change-second-line with-this
3 change-third-line  with-that

$ awk 'FNR==NR{arr[$1]=substr($0,index($0,$2));next}FNR in arr{print arr[FNR];next}1' fileB fileA
poo    foo
change-second-line with-this
change-third-line  with-that

# OR will be faster too
$ awk 'FNR==NR{arr[$1]=substr($0,length($1)+2);next}FNR in arr{print arr[FNR];next}1' fileB fileA
poo    foo
change-second-line with-this
change-third-line  with-that
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download