Reputation: 23
I have two files:
fileA
:
date >> /root/kvno.out
kvno serverXXX\$ >> /root/kvno.out
fileB
:
foobar
I need to create a new file, fileC
, with the same contents as fileA
, except with the string XXX
being replaced with the contents of fileB
:
date >> /root/kvno.out
kvno serverfoobar\$ >> /root/kvno.out
I'd like to do this using sed
.
I tried some of the examples I found but I only get the contents of fileB
in fileC
.
Upvotes: 2
Views: 141
Reputation: 58420
This might work for you (GNU sed):
sed '1{h;d};/XXX/{G;s/XXX\(.*\)\n\(.*\)/\2\1/}' fileB fileA >fileC
EDIT:
alternatively:
sed 's|XXX|'$(tr -d '\n' <fileB)'|' fileA >fileC
Upvotes: 2
Reputation: 246807
while IFS= read -r line; do
echo "${line/XXX/$(< fileB)}"
done < fileA > fileC
Upvotes: 2
Reputation: 203512
sed is an excellent tool for simple substitutions on a single line. For anything else, just use awk:
awk 'NR==FNR{b=b s $0; s=ORS; next} {sub(/XXX/,b)} 1' fileB fileA
Upvotes: 0
Reputation: 47267
There are some ambiguities with your question, but this works if I understood your requirements correctly:
#!/bin/bash
string=$(cat fileB)
sed "s/XXX/$string/g" < fileA > fileC
Caveat: fileB
cannot contain /
Explanation:
string=$(cat fileB)
: save the contents of fileB
to a variable called string
sed "s/XXX/$string/g": use
sedto replace all occurrences of
XXXwith what is inside the variable
$string. (The
g` part means replace-all)< fileA
: input redirection - use fileA
as input> fileC
: output redirection - output to fileC
Upvotes: 1