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

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
Alex Kurkin
  • 1,069
  • 10
  • 17

4 Answers4

4

How about:

sed `sed 's|\(.*\) \(.*\)|s/\1/\2/|' input` output
Beta
  • 96,650
  • 16
  • 149
  • 150
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
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
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.

Erik
  • 88,732
  • 13
  • 198
  • 189
  • Also consider `perl -pe` as a general purpose, more powerful `sed`. – Ben Mar 12 '11 at 16:31
  • Thanks, I'd found solution like you suggested, but I couldn't use it because of error: bash: syntax error near unexpected token `done' – Alex Kurkin Mar 12 '11 at 16:35
0

ok, I came across this solution:

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