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?
Best Answer
Using
awk
:Here, we pass line numbers as an awk
-v
ariable ina='...'
(for fileA) andb='...'
(for fileB), then wesplit()
them into an array on comma character as the separator (note thata
andb
were variables, while nowax
andbx
are arrays).then we build a another
mapping
array fromax
andbx
arrays to map the lines which those should be replaced in fileA with the ones from fileB;now keys (or indexes) of the
mapping
array is line numbers of the fileB and the values of these keys are the line numbers of the fileA, as below:the
mapping
array is:so now what we need, that is, just to read the line numbers from fileB that match with the keys above (FNRs of
1
,2
,5
and8
), so we do that with:OK, now what is the value of the
mapping[FNR]
? if you check themapping
array above, that would be:so we used the value of
mapping
array as the key for thehold
array andhold
array is now contains:now the last step is to use keys in
hold
array as the matched line number in fileA and replace that lines with the values of that key from thehold
array if that line number found in the array or print the line itself if not found (Ternary operator:condition? if-true : if-false
), and we do that with: