Abhishek Attri
Abhishek Attri

Reputation: 114

Why isn't this sed command working for the regex?

I want to remove the multi-line comments in Java using sed command. The regex is working if we use character ranges like a-zA-Z0-9 etc. but not in case of word character like \w\S.

Test-File content:

hello world
/* abcd
efgh*/
world hello

Command used :

sed -i -e  "s/\/\*[\s\S]\*\///" <file>

Expected results:

hello world
world hello

Actual results:

hello world
 abcd
efgh*/
world hello

Upvotes: 2

Views: 71

Answers (2)

Lars
Lars

Reputation: 3930

It is possible with sed, but not so easy.

sed ':x ; /^\/\*/ { N ; s/.*\*\/// ; /^$/d ; bx }' file
  • :x is a label
  • /^\/\*/ is /*
  • N append line from the input to the pattern space
  • s/.*\*\/// replace any {...}*/
  • /^$/d remove empty line
  • bx jumps unconditional to :x

Find more here in the documentation

Upvotes: 1

Pedro Lobito
Pedro Lobito

Reputation: 99071

You can use grep with a regex (-E) and inverted matches (-v), i.e.:

grep -Ev '(\/\*|\*\/)' < text.txt

Output:

hello world
world hello

Upvotes: 1

Related Questions