1

I have an file (hosts.txt) and many lines in that file are comments. How do I remove that comments?

5 Answers 5

2
sed '/^\#/d' myFile > tt
mv tt myFile 

What happens here:

sed '/^#/d' myFile removes all lines starting with # from the file myFile and outputs the result in the console, > tt redirects the output into a temporary file called tt, mv tt myFile moves the temporary file tt to myFile.

4
  • I would make the mv command conditional on sed completing successfully: sed '/^\#/d' myFile > tt && mv tt myFile -- or let sed handle the temp file: sed -i '/^\#/d' myFile Jun 12, 2015 at 15:09
  • Yes you could do that , but it is unlikely to fail :) Jun 12, 2015 at 15:15
  • Two commands for one simple task? And \# isn't necessary, # is enough.
    – A.B.
    Jun 12, 2015 at 15:17
  • @A.B. yes , that could be an optimization ^_^ . two commands to maintain simplicity Jun 12, 2015 at 15:24
0

You can use the sed Command and redirect the result to a new file by typing:

sed '/^\#/d' hosts.txt > cleaned.txt
0

You can use -i to edit files in place.

sed -i '/^#/d' hosts.txt

Or with a backup

sed -ibak '/^#/d' hosts.txt

from man sed

-i[SUFFIX], --in-place[=SUFFIX]
      edit files in place (makes backup if SUFFIX supplied)
0

you can use this:

sed '/^#/ d' < inputFile.txt > outputFile.txt
0
0

You can use Vim in Ex mode:

ex -sc g/^#/d -cx hosts.txt
  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 .