Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing patterns using sed

Tags:

unix

sed

I want to replace a pattern something like :

make_pair(obj1.get<1>(), obj2.get<2>());

to:

make_pair(get<1>(obj1), get<2>(obj2));

Tried with: sed -i'' -e 's/(\(.*\)./get<1>(\1)/g' file_name

But getting wrong result.

How to capture tokens before a pattern?

Note that it should also work with make_pair(obj1[I].get<1>(), obj2[I].get<2>()); string.

like image 497
noOne Avatar asked May 24 '26 13:05

noOne


2 Answers

You may use

sed -i'' -E 's/([[:alnum:]]*(\[[[:alnum:]]*])*)\.get(<[^><]*>)\(\)/get\3(\1)/g'  filename

POSIX ERE pattern details

  • ([[:alnum:]]*(\[[[:alnum:]]*])*) - Group 1:
    • [[:alnum:]]* - 0 or more alphanumeric chars
    • (\[[[:alnum:]]*])* - 0 or more repetitions of
      • \[ - a [ char
      • [[:alnum:]]* - 0 or more alphanumeric chars
      • ] - a ] char.
  • \.get - a .get substring
  • (<[^><]*>) - Group 3: a <, then 0+ chars other than < and > and then >
  • \(\) - an empty pair of brackets ().

Online demo:

s="make_pair(obj1[I].get<1>(), obj2[I].get<2>());"
sed -E 's/([[:alnum:]]*(\[[[:alnum:]]*])*)\.get(<[^><]*>)\(\)/get\3(\1)/g' <<< "$s"
# => make_pair(get<1>(obj1[I]), get<2>(obj2[I]));
like image 51
Wiktor Stribiżew Avatar answered May 30 '26 07:05

Wiktor Stribiżew


Try this please, see if it's what you wanted:

$ cat file_name
make_pair(obj1.get<1>(), obj2.get<2>());

$ sed -e 's/\([[:alnum:]]*\)\.\([[:alnum:]<>]*\)()/\2.(\1)/g' file_name
make_pair(get<1>.(obj1), get<2>.(obj2));

I removed -i'' switch, add it back when you see the result is correct for you.

like image 33
Tiw Avatar answered May 30 '26 06:05

Tiw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!