Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a file and removing certain lines

Tags:

bash

shell

I want to loop through a file and remove certain lines. Example file:

test.txt

a
b
c
d

What I have:

FILE=/tmp/test.txt
while read FILE
do
  # if the line starts with b delete it otherwise leave it there
  ?
done
like image 745
Bill Avatar asked Dec 04 '22 10:12

Bill


2 Answers

This is a job for sed - the UNIX stream editor:

(sed '/^b/d' yourfile > yourfile~ && mv yourfile~ yourfile) || rm yourfile~

The command will delete all lines which begin with a b and writes the remaing lines to a backup file. If this succeed the backup file will be renamed to the original file if it fails the backup file will be deleted.

like image 128
hek2mgl Avatar answered Dec 27 '22 05:12

hek2mgl


you could do it with a grep oneliner :

grep -v "^b" test.txt > newfile
like image 43
DRC Avatar answered Dec 27 '22 03:12

DRC