Home > Software design >  How to replace next word after a match in perl or sed expression?
How to replace next word after a match in perl or sed expression?

Time:09-08

I'm trying to replace doxygen comment from a file with swift comments.

e.g: /// \param foo should became /// - Parameter foo: with foo

So far I have

gsed -i 's/\\param/\- Parameter/g' my_file or perl -pe 's/\\param/\- Parameter/g'

I'd like to replace the following word (foo) after my expression with word: (foo:)

I didn't manage to find a good expression for that. Ideally, something that work on Linux and macOS

CodePudding user response:

In perl you can capture and put back the word with $1 (first parentheses).

s/\\param\s (. )/- Parameter $1:/g

. will capture the rest of that line. If that is something you don't want, and just want to capture the first word, you can use \S or \w or whatever other character class that matches the characters you want to capture, e.g. [a-z_-] .

In sed it is probably \1.

CodePudding user response:

Using sed

$ sed -E 's/\\(param)( [^ ]*)/- \u\1eter\2:/' input_file
/// - Parameter foo:

CodePudding user response:

You could use pattern with a single capture group, and use that group with \1 in the replacement.

sed -E 's/\\param[[:space:]] ([^[:space:]] )/- Parameter \1:/g' my_file

The pattern matches:

  • \\param Match \param
  • [[:space:]] Match 1 spaces
  • ([^[:space:]] ) Capture group 1, match 1 non whitespace chars

Output

- Parameter foo:

If you validated the output, then you can change sed -E to sed -Ei to do the replacement.

  • Related