SED : How to replace a character within a matched pattern using ampersand (&)

社会主义新天地 提交于 2019-12-03 05:53:16

问题


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 ?

For example, if & contains the string "apple1", how can I use & to make the string to "apple2" (i.e replace 1 by 2) ?


回答1:


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; }'

This means that you want to execute the command substitution only on the lines that matches the pattern /apple./.




回答2:


You can also use a capture group. A capture is used to grab a part of the match and save it into an auxiliary variable, that is named numerically in the order that the capture appears.

echo apple1 | sed -e 's/\(a\)\(p*\)\(le\)1/\1\2\32/g'

We used three captures:

  1. The first one, stored in \1, contains an "a"
  2. The second one, stored in \2, contains a sequence of "p"s (in the example it contains "pp")
  3. The third one, stored in \3, contains the sequence "le"

Now we can print the replacement using the matches we captured: \1\2\32. Notice that we are using 3 capture values to generate "apple" and then we append a 2. This wont be interpreted as variable \32 because we can only have a total of 9 captures.

Hope this helps =)




回答3:


you can first match a pattern and then change the text if matched:

echo "apple1" | sed '/apple/s/1/2/'    # gives you "apple2"

this code changes 1 to 2 in all lines containing apple




回答4:


This might work for you (GNU sed and Bash):

sed 's/apple1/sed "s|1|2|" <<<"&"/e' file


来源:https://stackoverflow.com/questions/12694562/sed-how-to-replace-a-character-within-a-matched-pattern-using-ampersand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!