如何用sed中的`pwd`结果替换令牌?

时间:2022-02-05 16:47:46

I'm trying to do something like this:

我正在尝试做这样的事情:

sed 's/#REPLACE-WITH-PATH/'`pwd`'/'

Unfortunately, I that errors out:

不幸的是,我错了:

sed: -e expression #1, char 23: unknown option to `s'

Why does this happen?

为什么会这样?

4 个解决方案

#1


You need to use a different character instead of /, eg.:

您需要使用不同的字符而不是/,例如:

sed 's?#REPLACE-WITH-PATH?'`pwd`'?'

because / appears in the pwd output.

因为/出现在pwd输出中。

#2


in sed, you can't use / directly, you must use '/'.

在sed中,你不能直接使用/,你必须使用'/'。

  #!/bin/bash
  dir=$`pwd`/
  ls -1 | sed  "s/^/${dir//\//\\/}/g"

#3


sed 's:#REPLACE-WITH-PATH:'`pwd`':' config.ini

The problem is one of escaping the output of pwd correctly. Fortunately, as in vim, sed supports using a different delimiter character. In this case, using the colon instead of slash as a delimiter avoids the escaping problem.

问题是正确地逃避pwd的输出。幸运的是,就像在vim中一样,sed支持使用不同的分隔符。在这种情况下,使用冒号而不是斜杠作为分隔符可以避免转义问题。

#4


instead of fumbling around with quotes like that, you can do it like this

而不是像这样的引号摸索,你可以这样做

#!/bin/bash
p=`pwd`
# pass the variable p to awk
awk -v p="$p" '$0~p{ gsub("REPLACE-WITH-PATH",p) }1' file >temp
mv temp file

or just bash

或者只是打击

p=`pwd`
while read line
do
    line=${line/REPLACE-WITH-PATH/$p}
    echo $line    
done < file > temp
mv temp file

#1


You need to use a different character instead of /, eg.:

您需要使用不同的字符而不是/,例如:

sed 's?#REPLACE-WITH-PATH?'`pwd`'?'

because / appears in the pwd output.

因为/出现在pwd输出中。

#2


in sed, you can't use / directly, you must use '/'.

在sed中,你不能直接使用/,你必须使用'/'。

  #!/bin/bash
  dir=$`pwd`/
  ls -1 | sed  "s/^/${dir//\//\\/}/g"

#3


sed 's:#REPLACE-WITH-PATH:'`pwd`':' config.ini

The problem is one of escaping the output of pwd correctly. Fortunately, as in vim, sed supports using a different delimiter character. In this case, using the colon instead of slash as a delimiter avoids the escaping problem.

问题是正确地逃避pwd的输出。幸运的是,就像在vim中一样,sed支持使用不同的分隔符。在这种情况下,使用冒号而不是斜杠作为分隔符可以避免转义问题。

#4


instead of fumbling around with quotes like that, you can do it like this

而不是像这样的引号摸索,你可以这样做

#!/bin/bash
p=`pwd`
# pass the variable p to awk
awk -v p="$p" '$0~p{ gsub("REPLACE-WITH-PATH",p) }1' file >temp
mv temp file

or just bash

或者只是打击

p=`pwd`
while read line
do
    line=${line/REPLACE-WITH-PATH/$p}
    echo $line    
done < file > temp
mv temp file