Remove line of text from multiple files in Linux

Solution 1:

If your version of sed allows the -i.bak flag (edit in place):

sed -i.bak '/line of text/d' * 

If not, simply put it in a bash loop:

for file in *.txt
do
    sed '/line of text/d' "$file" > "$file".new_file.txt
done

Solution 2:

To find a pattern and remove the line containing the pattern below command can be used

find . -name "*" -type f | xargs sed -i -e '/<PATTERN>/d'

Example : if you want to remove the line containing word sleep in all the xml files

find . -name "*.xml" -type f | xargs sed -i -e '/sleep/d'

NOTE : Be careful before choosing a pattern as it will delete the line recursively in all the files in the current directory hierarchy :)

Solution 3:

Consider grep -v:

for thefile in *.txt ; do
   grep -v "text to remove" $thefile > $thefile.$$.tmp
   mv $thefile.$$.tmp $thefile
done

Grep -v shows all lines except those that match, they go into a temp file, and then the tmpfile is moved back to the old file name.