Skip to main content
Became Hot Network Question
edited tags
Link
αғsнιη
  • 41.9k
  • 17
  • 75
  • 117
Source Link

replace lines in one file with lines in another by line number

I have a fileA.txt with many lines and I want to replace specific lines with other specific lines from a second file fileB.txt which also has many lines

For example: fileA.txt

Italy
Korea
USA
England
Peru
Japan
Uruguay

fileB.txt

Argentina
Switzerland
Spain
Greece
Denmark
Singapore
Thailand
Colombia

I want to replace line 2, 4, 5 and 7 in the first file with lines 1, 2, 5 and 8 from the second file:

Output:

Italy
Argentina
USA
Switzerland
Denmark
Japan
Colombia

I guess I can do it with awk or sed but if awk this code does not seems provide the information of the lines of the second file:

awk 'NR==FNR{ a[$2]=$1; next }FNR in a{ $0=a[FNR] }1' fileA.txt fileB.txt

Any suggestion?