I have a file that at some point contains a line like the following:
VIRTUAL_ENV="/afs/sern.ch/user/l/lronhubbard/virtual_environment"
It is the sole line in the file that begins with VIRTUAL_ENV
. Using a script, I want to replace this line with the following lines:
directory_bin="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
directory_env="$(dirname "${directory_bin}")"
VIRTUAL_ENV="${directory_env}"
How could this be done?
To start with, I've got the replacement lines stored in a here document in the script:
IFS= read -d '' text << "EOF"
directory_bin="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
directory_env="$(dirname "${directory_bin}")"
VIRTUAL_ENV="${directory_env}"
EOF
Next, I can replace the line in the file with something else (here, xxx
) using sed
:
sed -i "s/^VIRTUAL_ENV.*/xxx/g" test.txt
Now, how can I use the defined here document variable ${text}
, with all of its newlines and whatnot, instead of xxx
in the sed
command?
EDIT: Following the suggestion by rslemos, I have implemented the following using a temporary file instead of a here document:
#!/bin/bash
temporary_filename="$(tempfile)"
cat > "${temporary_filename}" << "EOF"
directory_bin="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
directory_env="$(dirname "${directory_bin}")"
VIRTUAL_ENV="${directory_env}"
EOF
sed -i "/^VIRTUAL_ENV.*/ {
r ${temporary_filename}
d
}" test.txt
rm "${temporary_filename}"
I'd still like to know how to use a here document directly so that I'm not unnecessarily using the hard drive.