jag7720
jag7720

Reputation: 23

Replace string in one file with contents of a second file

I have two files:

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

Answers (4)

potong
potong

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

glenn jackman
glenn jackman

Reputation: 246807

while IFS= read -r line; do
    echo "${line/XXX/$(< fileB)}"
done < fileA > fileC

Upvotes: 2

Ed Morton
Ed Morton

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

sampson-chen
sampson-chen

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": usesedto replace all occurrences ofXXXwith what is inside the variable$string. (Theg` part means replace-all)
  • < fileA: input redirection - use fileA as input
  • > fileC: output redirection - output to fileC

Upvotes: 1

Related Questions