简体   繁体   中英

sed order of disjunction matches

Given the input file text.txt

First token second pattern, second pattern.

And running:

sed -r -i "s/pattern|second pattern/REPLACE/g" input.txt

I get the new input.txt:

First token REPLACE, REPLACE.

It looks like second pattern is applied first here to match the contents of input.txt.

What is the order in which the disjuctions in sed are matching with the input text in sed?

Is there a way to specify the order in which disjunctions of matches should be applied, that works together with the -i inline command?

Not sure exactly what the sed regex engine is doing with the alternation ( | ) operator, but one way to get your desired result might be to separate into two regex statements in sed:

sed -r -i "s/pattern/REPLACE/g;s/second pattern/REPLACE/g"

This should give you total unambiguous control over the order in which the substitutions are applied, while all still happening in one sed invocation that works well with the inplace editing ( -i ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM