A
A
Aoeu2017-03-14 06:34:31
bash
Aoeu, 2017-03-14 06:34:31

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

The same command has a different output depending on whether it is executed from a script or from the console. I don't understand why. I can make the output the same by adding 2 more slashes to the sed, like this: sed 's/5/\\\\n/' but I don't understand why it is necessary to do this and why it doesn't work without it.
Update
From mana to bash:
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.

Backticks are considered obsolete, and when used, backslashes are treated like regular characters, unless they are followed by $, `, or \. When using brackets, everything is done as in the console.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
X
xibir, 2017-03-14
@Aoeu

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

Можно вместо `........` использовать $(..........), тогда будет работать как в первом случае

K
krypt3r, 2017-03-14
@krypt3r

echo -en '123\n456' | sed 's/5/\n/'

M
Maxim Vyaznikov, 2017-03-14
@rv9ufz

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

Those. the second \n, obtained as a result of processing by sed, is for some reason interpreted as a line break, but it’s not clear why offhand.

C
CityCat4, 2017-03-14
@CityCat4

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 question

Ask a Question

731 491 924 answers to any question