Reputation: 315
Suppose I have a text with the following content, with the file name test.txt
.
anmn gzcn anmn
devy dybu devy
emli ixco emli
udnx qmse udnx
lhdh hcdi lhdh
I need to replace the characters in column 3 with preset content.
The preset content is stored in another file, for example file1.txt
.
msit
ccps
ybwg
kgjs
uxxs
It is worth noting that the replacement characters in these two files are not in the same order, and their corresponding replacement relationships are as follows.
anmn -> ybwg
devy -> kgjs
emli -> msit
udnx -> uxxs
lhdh -> ccps
The expected output would be:
anmn gzcn ybwg
devy dybu kgjs
emli ixco msit
udnx qmse uxxs
lhdh hcdi ccps
Is it possible to do this through a simple shell script?
Upvotes: 0
Views: 962
Reputation: 12867
Assuming the replacement values are in a file file1.txt:
anmn ybwg
devy kgjs
emli msit
udnx uxxs
lhdh ccps
You can use awk:
awk 'FNR==NR { map[$1]=$2;next } { $3=map[$3]}1' file1.txt text.txt
Process the file with the replacements first (FNR==NR) and create an array map with the first space separated field as the index and the second space separated field ($1) as the value. Then when processing the second file, set the third space separated field to the value of the third field index in map and also set the output record separator to be the same as the input record separator. Print all records by specifying 1.
Upvotes: 3