如何使用与号(&)替换匹配模式中的字符 [英] How to replace a character within a matched pattern using ampersand (&)
问题描述
当我们使用sed匹配模式时,匹配的模式存储在&"变量中.有没有办法使用&符本身替换此匹配模式中的字符?
When we match a pattern using sed, the matched pattern is stored in the "ampersand" (&) variable. IS there a way to replace a character in this matched pattern using the ampersand itself ?
例如,如果&包含字符串"apple1",该如何使用&将字符串设置为"apple2"(即1替换为2)?
For example, if & contains the string "apple1", how can I use & to make the string to "apple2" (i.e replace 1 by 2) ?
推荐答案
如果我猜对了,那么您想要做的就是以匹配的模式应用替换.您不能使用&
来执行此操作.您要改为执行此操作:
If I guessed right, what you want to do is to apply a subsitution in a pattern matched. You can't do that using &
. You want to do this instead:
echo apple1 apple3 apple1 apple2 botemo1 | sed '/apple./ { s/apple1/apple2/g; }'
这意味着您只想在与模式/apple./
匹配的行上执行命令替换.
This means that you want to execute the command substitution only on the lines that matches the pattern /apple./
.
这篇关于如何使用与号(&)替换匹配模式中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!