使用sed从字符串中删除子字符串

rlu*_*uks 11 bash substring sed

我试图使用sed从变量中删除子字符串,如下所示:

PRINT_THIS="`echo "$fullpath" | sed 's/${rootpath}//' -`"
Run Code Online (Sandbox Code Playgroud)

哪里

fullpath="/media/some path/dir/helloworld/src"
rootpath=/media/some path/dir
Run Code Online (Sandbox Code Playgroud)

我想像这样回应其余的完整路径(我在整堆目录中使用它,所以我需要将它存储在变量中并自动执行

echo "helloworld/src"
Run Code Online (Sandbox Code Playgroud)

使用变量就可以了

echo "Directory: $PRINT_THIS"
Run Code Online (Sandbox Code Playgroud)

问题是,我无法获取sed删除子字符串,我做错了什么?谢谢

Mat*_*Mat 28

你不需要sed,bash单独就足够了:

$ fullpath="/media/some path/dir/helloworld/src"
$ rootpath="/media/some path/dir"
$ echo ${fullpath#${rootpath}}
/helloworld/src
$ echo ${fullpath#${rootpath}/}
helloworld/src
$ rootpath=unrelated
$ echo ${fullpath#${rootpath}/}
/media/some path/dir/helloworld/src
Run Code Online (Sandbox Code Playgroud)

查看String操作文档.


Gil*_*not 9

要在sed中使用变量,必须像这样使用它:

sed "s@$variable@@g" FILE
Run Code Online (Sandbox Code Playgroud)

两件事情 :

  • 我使用双引号(shell不用单引号扩展变量)
  • 我使用另一个与路径中的斜杠不冲突的分隔符

例如:

$ rootpath="/media/some path/dir"
$ fullpath="/media/some path/dir/helloworld/src"
$ echo "$fullpath"
/media/some path/dir/helloworld/src
$ echo "$fullpath" | sed "s@$rootpath@@"
/helloworld/src
Run Code Online (Sandbox Code Playgroud)