-1

I'm trying to make a simple bash script that takes an input file and replaces placeholders like &date by the actual value (the date in this case)

Example:

text=$(sed -e "s/&file/$FILE/" -e "s/&date/$DATE/" $FILE)
echo $text

Problems:

  1. The newlines are removed, all the lines are jumbled together.
  2. Things like /****** placed in the start of the file are changed to /bin /boot etc (so the paths are resolved). *****/ will also be replaced.

Example:

Input:

/**********************************
hello
**********************************/

Output (line broken in the middle to make it readable):

/bin /boot /dev /etc /home /lib /lib64 /mnt
/opt /proc /root /run /sbin /srv /sys /tmp /usr /var hello parent/ parent_neighbor/

I guess I need to escape the file, but I could not find anywhere how to do it.

RedBorg
  • 145
  • 1
  • 7
  • 3
    Double-quote your shell variable references. Specifically, use `echo "$text"` instead of just `echo $text`. Also, get in the habit of running your scripts through [shellcheck.net](https://www.shellcheck.net), since it's good at pointing out common mistakes like this. – Gordon Davisson Nov 02 '18 at 00:54
  • @GordonDavisson I tried putting quotes everywhere, except on the echo! I thought it was sed fault, but thinking about it, you’re right. – RedBorg Nov 02 '18 at 10:53

1 Answers1

1

The expansion of the root directory is happening because '/***********' is being interpreted by Bash pathname expansion as "root directory wildcard wildcard wildcard......"

I'd not even use sed for this, it's regex syntax is kind of unpleasant. How about Perl:

text=$(perl -pe 's/&file/'"$FILE"'/g; s/&date/'"$DATE"'/g' $FILE)
echo "$text"

as @Gordon Davisson said in the comment, the key here is to quote "$text" when it's used as an argument to echo so Bash doesn't treat "/***" as a path and expand it before echo is even invoked.

Edit: here's a link: http://wiki.bash-hackers.org/syntax/expansion/globs

Z4-tier
  • 7,287
  • 3
  • 26
  • 42
  • I’m gonna select you cause Gordon didn’t put in an answer, although you don’t have to go with perl – RedBorg Nov 02 '18 at 10:54