user465465
user465465

Reputation: 441

Cat here document escape all variable but one

I have to write to a file with some bash script. To substitute the variables we can use simply EOF and we escape the substitution with \. But, I want to escape everything, so, I can use 'EOF' and also want to substitute one variable, then how?.

 cat > myfile <<'EOF'
    $a
    $b
    $c
    $d
    $e
    $f
    $g
   .....
   .....
   $multiple lines like this
   EOF

I want to substitute only one variable let $c with it's value. How can I do in this case?. I can't use \ without quoting EOF escaping all the lines as there are many lines.

I just want to escape all the variable substitution('EOF') but want to substitute one variable with its value(How?).

Upvotes: 1

Views: 407

Answers (1)

John1024
John1024

Reputation: 113844

To avoid escaping the many variables but still substitute for one of them, try:

$ cat script
sed 's/$c/3/' >myfile <<'EOF'
    $a
    $b
    $c
   $multiple lines like this
EOF

Let's run the script and examine the output file:

$ bash script
$ cat myfile 
    $a
    $b
    3
   $multiple lines like this

Alternative

This version allows for a variable $c and, thus, may be more flexible:

$ cat script
c=New
sed "s/\$c/$c/" >myfile <<'EOF'
    $a
    $b
    $c
   $multiple lines like this
EOF

Execution of this results in:

$ bash script
$ cat myfile 
    $a
    $b
    New
   $multiple lines like this

Upvotes: 2

Related Questions