How to remove a text from file/files using grep

Posted by : on

Category : Bash

However in practice we need to remove some text from a file or from multiple files. Removing text from files manually is a tough task. Here is a sample example to do this:

Create a script

  • Create a file like SOME_NAME.sh
  • Write following lines of code in that file
for thefile in *.txt ; do
   grep -v "YOUR_TEXT_TO_REMOVE" $thefile > $thefile.$$.tmp
   mv $thefile.$$.tmp $thefile
done

You can use any extension in place of txt according to your requirement.

Explanation

grep -v "YOUR_TEXT_TO_REMOVE" $thefile > $thefile.$$.tmp returns the content of all .txt files in that directory YOUR_TEXT_TO_REMOVE and write that output in a tempfile then replace new file with that original one.

Running script

  • To run script just run sh SOME_NAME.sh

Enjoy !!!



About Ram Laxman Yadav
Ram Laxman Yadav

Senior Software Engineering Professional | Tech Enthusiast | Mentor | Payments | Hospitality | E-Commerce, based in NCR, India

Email : info@ramlaxman.co.in

Website : https://ramlaxman.co.in