using sed to change particular parts of expression pattern

Viewed 141

How can I change all strings in the file, which have the pattern: lowercase sequences of letters separated by one underscore and after last sequence are parentheses. I need change it to sequences, which are not separated by underscore and any letter after underscore is changed to uppercase letter?

For example: this_is_my_task() change to thisIsMyTask(). I need to do it with sed.

But the program should not change string like: this_is____my_task(), because there are 4 underscores in a row.

Program should not change these strings: ___this_is_my_task() or, because of there are underscores in the beginning of the first string.

I have tried this: sed -r 's/([a-z]+)_([a-z]+)\(\)/\1\u\2()/' file.c, but this will change it only to this_is_myTask()

1 Answers

The best approach is using Perl:

perl -pe 's{\b[a-z]+(?:_[a-z]+)+\(\)}{$&=~s/_([a-z])/\u$1/gr}ge' file.c

See the online demo and the first regex demo, it matches

  • \b - word boundary
  • [a-z]+ - 1+ lowercase ASCII letters
  • (?:_[a-z]+)+ - one or more occurrences of _ and 1+ lowercase ASCII letters
  • \(\) - a () substring.

Once there is a match, the match value ($&) is replaced using _([a-z]) pattern (_ and then a lowercase letter in Group 1) that is replaced with the uppercase letter (\u$1).

With sed, you may use

sed -E ':a; s/\b([a-z][A-Za-z]*)_([a-z]+(_[a-z]+)*\(\))/\1\u\2/; ta' file.c

Or

sed -E ':a; s/\b([[:lower:]][[:alpha:]]*)_([[:lower:]]+(_[[:lower:]]+)*\(\))/\1\u\2/; ta' file.c

See the online demo

Details

  • :a - sets the label with name a
  • s/\b([a-z][A-Za-z]*)_([a-z]+(_[a-z]+)*\(\))/\1\u\2/ - replaces

    • \b - word boundary
    • ([a-z][A-Za-z]*) - Group 1: a lowercase letter followed with 0+ letters
    • _ - an underscore
    • ([a-z]+(_[a-z]+)*\(\)) - Group 2:
      • [a-z]+ - 1+ lowercase letters followed with
      • (_[a-z]+)* - 0 or more occurrences of underscores and then 1+ lowercase letters and then followed with
      • () - a () substring

    with the Group 1 and Group 2 values with the first char in Group 2 turned to upper

  • ta - on a successful replace, jumps to label a position.
Related