1

I would like to remove a string pattern which like this

You should not remove this /*This is the part should remove*/ You
should not remove this

I would like to remove all the text inside the /* and */.

2 Answers 2

2

In the interests of teach-a-man-to-fish vs. give-a-man-a-fish I'm linking you to a tutorial on regular expressions. regular-expressions.info/quickstart.html

In case you need a quick solution, here is what you would do: Open the file in vim, and type the following:

:s/\/\*.*?\*\/ /g

This is supposed to replace all of your strings beginning /* and ending */ with a space. I linked you to the regex tutorial first in case I butchered the expression I wrote. Either read the tutorial and write your own command, or make a backup before you use the line above.

2
  • Just forgot the any char, but points for remembering to make it non-greedy! 's/\/\*.*?\*\/ /g'
    – Nicholi
    Jul 27, 2011 at 17:18
  • Can't believe I forgot the magic dot! Just fixed it.
    – Yitzchak
    Jul 27, 2011 at 19:09
1

Try the following quick and dirty sed line:

sed -e 's@/\*.*\*/@@' file

This will show you the output, but will not actually modify the file, once you've run it and confirmed that it makes the changes you want, then put -i before the -e to tell it to change the file in place.

What it actually does it takes everything between the /* and */ and substitutes it with nothing (essentially deleting it), it will also get the /* and */ portion as well though.

I give you the non-modification method first just in case I butchered my regular expression (working off memory, and no access to sed on current machine to test right quick). Also be aware that this won't work if the text to be remove cross lines, as sed works on each line individually. If you need a program to work on multiple lines of text at once, you'll need either awk or possibly perl (neither of which I know enough to offer code suggestions for).

1
  • Nice answer. Worked perfectly.
    – Ajay Kumar
    Feb 17, 2021 at 21:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .