0

i am creating a script that will take a csv file and make an XML file. The script will also take user entered data to go in the xml as well. I have created a script that will make my XML, but i am having problems entering my read in variable at the start of the file.

Ultimately there will be a longer line being entered, with 3 variables in the line - i am just writing the basics at the minute.

My problem is i am unable to read in the variable $BUS into ed command. I have read that it is possible, but i have been unable to make it work.

i tried my EOF with and without the single quote.

 echo "Enter BUS name"
        read BUS

echo $BUS

awk -f xmlbody $FILE  > result.xml
file=result.xml

ed -s $file <<'EOF'
0a
<?xml version="1.0" encoding="utf-8"?>
$BUS
<Data>
.
$a
</Data>
.
w
EOF

exit 0
Red_badger
  • 119
  • 1
  • 15

1 Answers1

1

From bash's manual :

If any characters in [the delimiter] are quoted, [...] the lines in the here-document are not expanded

You must avoid quoting your heredoc delimiter (here EOF). The following should work :

ed -s $file <<EOF
0a
<?xml version="1.0" encoding="utf-8"?>
$BUS
<Data>
.
\$a
</Data>
.
w
EOF
Aaron
  • 24,009
  • 2
  • 33
  • 57
  • Hi All, thanks for the prompt responses. i have tried with the heredoc delimiter unquoted already. this is the response. I ran the script with set -x the first line of the result.xml file is printed. + ed -s result.xml ? + exit 0 – Red_badger Jan 17 '20 at 12:51
  • Also by unquoting, will i lose the ability to add to the end of the file - as signified by $a ? – Red_badger Jan 17 '20 at 12:54
  • @Red_badger sorry I hadn't considered `$a` was an `ed` instruction, so you would indeed need to escape the `$` so that it won't be expanded to the value of a `$a` variable. I've edited my answer in that regard – Aaron Jan 17 '20 at 13:13
  • Regarding your continuing problem : your `set -x` logs show that the `$BUS` variable is expanded to the empty string, which would happen if the variable was undefined when it's expanded. Given the code you posted, I see little reason it could happen (maybe exotic characters in your variable names which would make them look similar but actually be different variable names?). Did you post the exact code you're using? The problem would typically happen if the variable definition was done inside a subshell, it wouldn't be propagated to the calling shell. – Aaron Jan 17 '20 at 13:18
  • Hi All, Thanks for you help. i spent a while trying to get this to work with ed, but could not. So i have used SED instead, probably not very elegant solution as it requires 3 lines, but as the file is not very big it serves my purpose. Thanks again – Red_badger Jan 17 '20 at 17:26