0

I have a file file.txt with this content: Hi {YOU}, it's {ME}

I would like to dynamically create a new file file1.txt like this

YOU=John
ME=Leonardo
cat ./file.txt | sed 'SED_COMMAND_HERE' > file1.txt

which content would be: Hi John, it's Leonardo

The sed command I tried so far is like this s#{\([A-Z]*\)}#'"$\1"'#g but the "substitution" part doesn't work correctly, it prints out Hi $YOU, it's $ME

anubhava
  • 761,203
  • 64
  • 569
  • 643
Leonardo Rossi
  • 2,922
  • 2
  • 20
  • 28
  • Those duplicates assume that I already know the name of the variable, but I have already solved that way. I would like that to be dynamic (i.e. I can add env variables and placeholder, without changing the `sed` command) – Leonardo Rossi Jun 21 '16 at 09:25

2 Answers2

1

You can use awk with 2 files.

$> cat file.txt
Hi {YOU}, it's {ME}

$> cat repl.txt
YOU=John
ME=Leonardo

$> awk -F= 'FNR==NR{a["{" $1 "}"]=$2; next} {for (i in a) gsub(i,a[i])}1' repl.txt file.txt
Hi John, it's Leonardo
  • First awk command goes through replacement file and stores each key-value in an array a be wrapping keys with { and }.
  • In second iteration we just replace each key by value in actual file.

Update:

To do this without creating repl.txt you can use `process substitution**:

awk -F= 'FNR==NR{a["{" $1 "}"]=$2; next} {
   for (i in a) gsub(i,a[i])} 1' <(( set -o posix ; set ) | grep -E '^(YOU|ME)=') file.txt
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • This works but I need to use a single file, and use env bash variables – Leonardo Rossi Jun 21 '16 at 09:22
  • To do this without creating `repl.txt` you can do: `awk -F= 'FNR==NR{a["{" $1 "}"]=$2; next} {for (i in a) gsub(i,a[i])}1' <(( set -o posix ; set ) | grep -E '^(YOU|ME)=') file.txt` (see updated) – anubhava Jun 21 '16 at 11:42
1

The sed utility can do multiple things to each input line:

$ sed -e "s/{YOU}/$YOU/" -e "s/{ME}/$ME/" inputfile.txt >outputfile.txt

This assumes that {YOU} and {ME} occurs only once each on the line, otherwise, just add g ("s/{YOU}/$YOU/g" etc.)

Kusalananda
  • 14,885
  • 3
  • 41
  • 52
  • This is what I am doing now, but I want it to be dynamic, so that I can add placeholders and env variable without changing the `sed` command script – Leonardo Rossi Jun 21 '16 at 09:21