查找和替换含SED非转义字符变量 [英] Find and replace variables containing non-escaped characters with sed

查看:591
本文介绍了查找和替换含SED非转义字符变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以利用这一点,找到飞的所有实例,并在我的文件虫子替换为:

  SED -i'S /飞/昆虫/ G'./animals.txt

我怎样才能找到一个BASH变量,并用另一个变量BASH取代它呢?例如:

 名称= $(回声飞)
类别= $(回声虫)
SED -iS / $名称/ $类/ G'./animals.txt

更新:

我使用GNU sed的版本4.2.1。当我尝试以下解决方案,它会报告这个错误:

 的sed:-e前pression#1,烧焦73:未知的选项'S'

更新:

我发现为什么错误来了。 $类别经常含有大量的符号(例如,/,$,@,!,支架,等)。

  AME = $(回声飞)
类别= $(回声中​​/教派)
SED -iS / $名称/ $类/ G./animals.txt

以上code将产生同样的错误:

 的sed:-e前pression#1,烧焦7:未知的选项'S'

有没有办法让 SED 完成替换,即使遇到这些符号?


解决方案

使用双引号

使用双引号,使外壳扩展变量,同时保持空白:

  SED -iS / $名称/ $类/ G./animals.txt

注意:如果你需要把反斜线在替换(例如,用于反向引用),则需要双斜杠(\\&安培;包含模式匹配):

使用单引号

如果您已经有很多shell元字符,你可以做这样的事情:

  SED -iS /'$模式'/'$类别/ G'./animals.txt



  

我发现为什么错误来了。 $类经常含有大量的符号(例如,/,$,@,!,支架,等)。


如果替换或更换部分包含像 / 字符,那么我们就可以使用不同的套 SED 分隔符。您可以使用类似 - @%; :| _ 等,这不会发生在你的替代和置换发生的任何字符。

I can use this, to find all instances of "fly" and replace it with "insect" in my file:

sed -i 's/fly/insect/g' ./animals.txt

How can I find a BASH variable and replace it with another BASH variable? E.g.:

name=$(echo "fly")
category=$(echo "insect")
sed -i 's/$name/$category/g' ./animals.txt

Update:

I am using GNU sed version 4.2.1. When I try the solutions below, it reports this error:

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

Update:

I discovered why the error is coming up. $category frequently contains lots of symbols (e.g. "/", "$", "@", "!", brackets, etc.).

ame=$(echo "fly")
category=$(echo "in/sect")
sed -i "s/$name/$category/g" ./animals.txt

The above code will create the same error:

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

Is there a way to let sed complete the replaces, even when it encounters these symbols?

解决方案

Using double quotes

Use double quotes to make the shell expand variables while keeping whitespace:

sed -i "s/$name/$category/g" ./animals.txt

Note: if you need to put backslashes in your replacement (e.g. for back references), you need double slashes (\& contains the pattern match):

Using single quotes

If you've a lot shell meta-characters, you can do something like this:

sed -i 's/'$pattern'/'$category'/g' ./animals.txt


I discovered why the error is coming up. $category frequently contains lots of symbols (e.g. "/", "$", "@", "!", brackets, etc.).

If the substitution or replacement portion contains characters like / then we can use different sets of sed delimiters. You can use something like - @ % , ; : | _ etc. any character that does not happen to occur in your substitution and replacement.

这篇关于查找和替换含SED非转义字符变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆