Bill
Bill

Reputation: 1247

Looping through a file and removing certain lines

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

Upvotes: 4

Views: 3268

Answers (4)

G. Cito
G. Cito

Reputation: 6378

"Perl ... it could be in your $PATH" :-)

Using a $SHELL for tiny textual tasks (i.e. sh, ksh, zsh, bash, tcsh,csh) on BSD, OSX, Linux, AIX, Solaris with the various "standard POSIX" versus BSD, Linux and GNU extensions to sed, grep and other utilities and taking care to account for gawk versus awk and the ancient versions of tools on many server systems ... can be hard.

perl -i.orig -ne 'print unless /^b/' test.txt

Did it work?

diff test.txt test.txt.orig

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 158010

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.

Upvotes: 9

Charles Duffy
Charles Duffy

Reputation: 295443

Easily done with bash built-in functionality:

while read -r; do
  [[ $REPLY = b* ]] || printf '%s\n' "$REPLY"
done <file >file.new
mv file.new file

Upvotes: 5

DRC
DRC

Reputation: 5048

you could do it with a grep oneliner :

grep -v "^b" test.txt > newfile

Upvotes: 4

Related Questions