How do I remove lines of a file which contain a specific string?

How do I remove lines of a file (hosts) which contain "adf.ly" string?


Solution 1:

using sed

Run this command:

sed -i '/adf\.ly/d' inputfile 

man sed

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

Using grep

Thanks for @kos notes:

grep -v "ad\.fly" inputFile  > outputfile

Solution 2:

The following will remove the lines containing "adf.ly" in filename.txt in-place:

sed -i '/adf\.ly/d' filename.txt

Use the above command without -i to test it before removing lines.

Solution 3:

Using awk (thanks to terdon for the shortened version):

< inputfile awk '!/adf\.ly/' > outputfile
  • < inputfile: redirects the content of inputfile to awk's stdin
  • > outputfile: redirects the content of awk's stdout to outputfile

awk command breakdown:

  • !/adf\.ly/: prints the record if not matching the adf\.ly regex

Using Perl (thanks to terdon for the shortened version):

< inputfile perl -ne '/adf\.ly/||print' > outputfile
  • -n: places a while (<>) {[...]} loop around the script
  • -e: reads the script from the arguments

Perl command breakdown:

  • /: starts the pattern
  • adf\.ly: matches an adf\.ly string
  • /stops the pattern
  • ||: executes the following command only if the pattern didn't match the line
  • print: prints the line