4

to remove comments (start with # and /* comment */) in settings.php, below command is just works fine:

sed '/^\#/d' settings.php > outp.txt
mv outp.txt settings.php
sed '/\/\*/,/*\//d; /^\/\//d; /^$/d;' settings.php > outp2.txt
mv outp2.txt settings.php
sed '/^$/d' settings.php > outp3.txt
mv outp3.txt settings.php

But how to remove comments in all files including in subdirectories?

2
  • FYI, you can use sed -i to do an in-place edit. Also, you are doing /^$/d twice. Mar 20, 2011 at 8:15
  • thanks. I'm newbie in using sed. I will look into it Mar 20, 2011 at 8:22

3 Answers 3

2

Starting from the directory you wish to traverse you can f.e. use find ./ -type f -name '*.php' -print0 | xargs -0 sed -i '/^\#/d'. xargs builds the argument list for sed for better performance and the -i option of sed replaces the pattern in-place (you don't have to use redirection).

EDIT: According to the manpage of find find ./ -name '*.php' -type f -print0 | xargs -0 sed -i '/^\#/d' is even faster, because it doesn't call stat on every file (-type option).

1
  • 1
    You might prefer to use the -print0 parameter to find and use xargs -0 - this will append \000 (chr(0), ascii character 0, 0x00, call it what you will) after each filename, and tells xargs to expect that character as a filename delimiter. This allows you to cleanly handle filenames with spaces in them.
    – Majenko
    Mar 20, 2011 at 9:04
1

You can sed 'in place' with -i. You can concat sed-commands with semicolons like this: 'c1;c2;c3' You can execute commands with find - no need for | xargs.

find ./somedir -name "*.php" -execdir sed -i '/^\#/d;/\/\*/,/*\//d; /^\/\//d; /^$/d;;/^$/d' {} + 

This works for gnu-find on linux; maybe your find doesn't have -execdir, -exec should work as well, and maybe it doesn't have +, then ";" would be a simple but not that fast solution, or using xargs as shown above by p.vitzliputzli with the improvement from Matt for filenames with whitespace and special characters is an alternative.

0

You can use Vim in Ex mode:

find -name '*.php' -exec ex -sc g/^#/d -cx {} ';'
  1. g global search

  2. d delete

  3. x save and close

You must log in to answer this question.

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