简体   繁体   中英

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

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

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

Output:

hello world
world hello

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM