1

how to replace strings in file, based on values from another file.

Example, 2 files - input, output

input:

12345 1

output:

(1,'a lot of text', 'some other info',0,null, 12345),
(2,'a lot of text', 'some other info',0,null, 12345),
(3,'a lot of text', 'some other info',0,null, 12345),
(4,'a lot of text', 'some other info',0,null, 12345),
(5,'a lot of text', 'some other info',0,null, 12345);

Needs to be done:

read values from file 'input', and replace all '12345' with '1' in file 'output'. Thanks for help in advance

4 Answers 4

4

How about:

sed `sed 's|\(.*\) \(.*\)|s/\1/\2/|' input` output
Sign up to request clarification or add additional context in comments.

Comments

2

No need to have AWK repeatedly call sed. Just have AWK read the first file into an array:

awk -F "[ )]" 'NR == FNR {a[$1] = $2; next} {sub($(NF-1), a[$(NF-1)]); print}' key-value-file main-file

Comments

0
cat input | while read src rep
do
  sed -i "s, $src), $rep),g" output
done

Remember to make a backup of "output".

EDIT: Also note that if "input" contains characters that are special to sed, this will fail. For plain letters/digits it'll work fine.

2 Comments

Also consider perl -pe as a general purpose, more powerful sed.
Thanks, I'd found solution like you suggested, but I couldn't use it because of error: bash: syntax error near unexpected token `done'
0

ok, I came across this solution:

cat input | awk '{ cmd = "sed s/," $1 ",/," $2 ",/g" " output > output.new"; print system(cmd) }'

1 Comment

No need for the cat; just give the file to awk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.