Differences between revisions 1 and 19 (spanning 18 versions)
Revision 1 as of 2012-03-21 17:23:44
Size: 1333
Editor: e36freak
Comment:
Revision 19 as of 2012-09-11 07:44:32
Size: 309
Editor: dslb-088-072-055-065
Comment:
Deletions are marked like this. Additions are marked like this.
Line 2: Line 2:
== How can i perform a substitution (s/foo/bar/) safely, without treating either value as a regular expression? == == Can I use something like templates with bash? ==
Bash does not have any native way to use templates. However, depending your actually goals may just evaluating the file with an new bash or shell instance could do the trick.
Line 4: Line 5:
Sed is not the right tool for this. At best, it will be an escaping nightmare, and extremely prone to bugs.

First, what are we performing the substitution on? If it's a string, it can be done very simply with a parameter expansion.

{{{
var='some string'
echo "${var//some/another}"
}}}

This is discussed in more detail in [[BashFAQ/100][Faq #100]].

If it's a file or stream, things get a bit trickier. One way to accomplish this would be to combine the previous method with [[BashFAQ/001][Faq #1]].

{{{
# file
while IFS= read -r line; do
  printf '%s\n' "${line//foo/bar}"
done < file

# command output
while IFS= read -r line; do
  printf '%s\n' "${line//foo/bar}"
done < <(my_command)

my_command | while IFS= read -r line; do
  printf '%s\n' "${line//foo/bar}"
done
}}}

The second of the two command examples there creates a subshell. See [[BashFAQ/024][Faq #24]] for more information on that.

Both of the above examples print to stdout. Neither actually edits the file in place. Of course this could be resolved with something like:
{{{
while IFS= read -r line; do
  printf '%s\n' "${line//foo/bar}"
done < file > new_file && mv new_file file
}}}
However, this is discussed on the [[TemplateFiles]]-Page

Can I use something like templates with bash?

Bash does not have any native way to use templates. However, depending your actually goals may just evaluating the file with an new bash or shell instance could do the trick.

However, this is discussed on the TemplateFiles-Page

BashFAQ/110 (last edited 2021-09-30 00:41:01 by emanuele6)