Shell script ing. Problem with replacing command in my script

In both cases, my Cygwin and my Linux box (Debian) have the same problem:

I am working in a shell script with some formatting identifiers, I want to add a backslash () before the appearance of a slash (/).

My sed script works well on my terminal:

# export someid="314-12345/08"
# echo "${someid}" | sed 's/\//\\\//'

Output:

314-12345\/08

But not so if I ran command substitution :

# someidformatted=`echo "${someid}" | sed 's/\//\\\//'`
sed: -e expression #1, char 9: unknown option to `s'

What am I missing here?

Thanks in advance.

+3
source share
2 answers

There is no obligation to use / as a delimiter for sed.

s/a/c/

Can be

s#a#c#

So in your case:

someidformatted=`echo "${someid}" | sed 's#\/#\\\/#'`

will do the job.

, /.

+13

. bash (1) man :

, , , $, ' \.. , , . $(command) ; .

, , , . , set -x:

# someidformatted=`echo "${someid}" | sed 's/\//\\\//'`
++ echo 314-12345/08
++ sed 's/\//\\//'
sed: 1: "s/\//\\//": bad flag in substitute command: '/'
+ someidformatted=
# someidformatted=$(echo "${someid}" | sed 's/\//\\\//')
++ echo 314-12345/08
++ sed 's/\//\\\//'
+ someidformatted='314-12345\/08'

, , \\ \. , $(command):

# someidformatted=$(echo "${someid}" | sed 's/\//\\\//')
+8

Source: https://habr.com/ru/post/1712444/


All Articles