Perl command line – replace multi line comments

Perl command line one liner can be used to replace text in a file using regular expressions (regex). It is very powerful approach for automating various tasks. Here is an example to remove multi line C style comments (/*..*/) from a file treating whole file as one string.

Data file

part1
/*
comment1
*/
part2
/* comment2 */
part3

Perl one liner to replace multi line comments

Here is the perl one liner to replace multi-line comments and its outcome.

perl -0 -p -e 's#/\*.*?\*/##gs' data1.txt
part1

part2

part3
Env: GNU bash, version 4.3.11

Few points to nore

  1. -0 causes the whole file to be treated as string
  2. Flag s (DOTALL) is to make dot matches witl everything including space.
  3. Flag g is for global replace (all occurences)
  4. .*? is for making the regex greedy
  5. We used # as regex delimiter for better readability
  6. One can use -i to modify the file directly. It should be used with caution though
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments