Use sed
to convert the second file into a sed
script that edits the first:
sed 's/\([^ ]*\) \(.*\)/s%\1_%\2_%/' file.2 > sed.script
sed -f sed.script file.txt
rm -f sed.script
No loops in the Bash code. Note the _
in the patterns; this is crucial to prevent Sample3
from mapping Sample300
to john.D00
.
If, as you should be, you are worried about interrupts and concurrent runs of the script, then (a) use mktemp
to generate a file name in place of sed.script
, and (b) trap interrupts etc to make sure the script file name is removed:
tmp=$(mktemp "${TMPDIR:-/tmp}/sed.script.XXXXXX")
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15
sed 's/\([^ ]*\) \(.*\)/s%\1_%\2_%/' file.2 > $tmp
sed -f $tmp file.txt
rm -f $tmp
trap 0