I’m trying to match the following:
A pattern begins with /* and ends with */\n(override\s+)public, tried doing something like this:
sed -n '/\/\*/,/\*\/\n(override\s+)public/p' file
And here I am asking you how to write that properly 🙂
If it’s possible to do with grep or awk – that’s an option, if it’s a one-liner in perl, that’s fine too.
PS. I’m not sure of sed regex syntax, but \s is meant to be a whitespace, ideally [\ \t\r\n].
EDIT:
Suppose you have:
/**
* Some comment goes here
*/
override public function ...
/**
* A comment for another function
*/
public function ...
The expression would give you these two results:
/**
* Some comment goes here
*/
override public
and
/**
* A comment for another function
*/
public
EDIT:
Even better, if someone could translate the below regex into sed, that would do the job.
/\/\*(!?\*\/)*\*\/\s*(overrides\s+)?public/gm
Note, that m flag means the regex is multiline, that is the negative lookahead group will match line ends too. But if that’s not possible, but matching line ends is still possible, then the expression would look like this:
/\/\*((!?\*\/)*$)*\*\/[\r\n\t\ ]*(overrides[\r\n\t\ ]+)?public/g
I think this will do what you want:
The
-0777is the perl convention for “read all offilein at once”, rather than the default of line-by-line.The
-ntells perl to not print the input file (as opposed to-pwhich does print it).The
-etells perl to read the program from the command line.The regex is largely as you wrote it, though I removed the comma bit since it wasn’t clear what you were trying to do. I used the reluctant
*?quantifier to match the shortest possible match, along with thesflag which treats the entire file as a ‘single line’ and which means that.*?matches across line boundaries when it otherwise would not.The
min theifclause causes the expression to evaluate to true if the regex matches. Thesat the end of the expression treats the input as a single line. Inside theifclause, we’re printing$1which is the first group matched by the regex. If you wanted to print the second group, you’d use$2.Updated: Changed the groups so it will print out the
overrideandpublic, madeoverrideoptional per your edit, changediftoforso it matches multiple instances of the pattern.