Answer the question
In order to leave comments, you need to log in
Bash how to escape characters?
In general, I can not figure it out, I have already killed a lot of time. Here is a synthetic example:
$ echo '123\n456' | sed 's/5/\\n/'
123\n4\n6
$ cat myecho
#!/bin/bash
str=`echo '123\n456' | sed 's/5/\\n/'`
echo $str
$ ./myecho
123\n4 6
When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are specially treated.
Answer the question
In order to leave comments, you need to log in
In the first case, sed gets two slashes
. In the second case, the double slash is processed FIRST with the backquote operator, i.e. it becomes one and sed gets ONE slash, so two more \\ must be added
Можно вместо `........` использовать $(..........), тогда будет работать как в первом случае
If you run the script with -x, you get:
++ echo '123\n456'
++ sed 's/5/\n/'
+ str='123\n4
6'
+ echo '123\n4' 6
123\n4 6
Because the console, when processing input , processes escaping again .
sed 's/5/\\\\n/' - when processing input, four \\\\ characters turn into two (every first is an escape, every second is an escape). When the command is processed, two \\ characters turn into one. The issue of shielding is perhaps one of the most confusing - sometimes you have to shield two or even three times!
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question