bash 使用sed从字符串中删除子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9861090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing substring out of string using sed
提问by rluks
I am trying to remove substring out of variable using sed like this:
我正在尝试使用 sed 从变量中删除子字符串,如下所示:
PRINT_THIS="`echo "$fullpath" | sed 's/${rootpath}//' -`"
where
在哪里
fullpath="/media/some path/dir/helloworld/src"
rootpath=/media/some path/dir
I want to echo just rest of the fullpath like this (i am using this on whole bunch of directories, so I need to store it in variables and do it automatically
我想像这样回显完整路径的其余部分(我在整个目录上使用它,所以我需要将它存储在变量中并自动执行
echo "helloworld/src"
using variable it would be
使用变量它会是
echo "Directory: $PRINT_THIS"
Problem is, I can not get sed to remove the substring, what I am I doing wrong? Thanks
问题是,我无法通过 sed 删除子字符串,我做错了什么?谢谢
回答by Mat
You don't need sed
for that, bash
alone is enough:
你不需要这样做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
Check out the String manipulationdocumentation.
查看字符串操作文档。
回答by Gilles Quenot
To use variables in sed, you must use it like this :
要在 sed 中使用变量,您必须像这样使用它:
sed "s@$variable@@g" FILE
two things :
两件事情 :
- I use double quotes (shell don't expand variables in single quotes)
- I use another separator that doesn't conflict with the slashes in your paths
- 我使用双引号(shell 不扩展单引号中的变量)
- 我使用另一个与路径中的斜杠不冲突的分隔符
Ex:
前任:
$ 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