How to replace a text pattern containing brackets?

2020-02-15 07:17发布

I want to replace a specific instruction containing brackets with another instruction recursively in all the files.

For example,

mov r1, [r1, r2]

with

sub [r8, r9], r10

When I use

 sed -i.bak "s/mov r1, [r1, r2]/sub [r8, r9], r10/g" file.S

it doesn't work.

How can I do that?

3条回答
女痞
2楼-- · 2020-02-15 07:29

Escaping the brackets -- [ ] -- in sed's substitute command will process your file the way you expect it to. Here is your command rewritten with the brackets escaped:

sed 's/mov r1, \[r1, r2\]/sub [r8, r9], r10/g' file.S
查看更多
男人必须洒脱
3楼-- · 2020-02-15 07:40

Two things.

  1. You need to escape the brackets in the match expression, they have special meaning in regular expressions.
  2. You should protect the sed script from shell expansion. Using double quotes forces expansions. Single quotes switches expansion off.

Thus:

's/mov r1, \[r1, r2\]/sub [r8, r9], r10/g'

While working out the correct script you can just skip the inline editing, maybe. Like so:

sed 's/mov r1, \[r1, r2\]/sub [r8, r9], r10/g' file.S
查看更多
趁早两清
4楼-- · 2020-02-15 07:43

Try with escaped brackets 's/mov r1, \[r1, r2\]/sub \[r8, r9\], r10/g'.

查看更多
登录 后发表回答