How to delete a given line from a file

I am writing a BASH script to integrate our intranet of our company with our postfix mail server. In one situation, the script should remove the line from the postfix virtual file, which takes the following form (for the most part): emailAddress username.

  xyx@abc.com xyz
     tuv@abc.com tuv
     lmn@abc.com lmn

my BASH script you need to read a file containing user names (one for each line) and delete the corresponding line from the virtual file. So let's say that he reads a line containing the username xyz; thus, in the example below, the variable $usr stores the value 'xyz' .

 touch virtual.tmp cat virtual | while read LINE ; do if [ "$LINE" != " $usr@abc.com $usr" ] ; then echo "$LINE" >> virtual.tmp fi done rm -rf virtual mv virtual.tmp virtual 

However, this code does not work and is probably not efficient, since all I want to do is delete the line based on the username. Presumably I may not have to read the entire file.

+4
source share
2 answers

Try sed with -i, for example:

 sed -i -e "/^ $usr@abc.com /d" virtual 

which should remove the line from the virtual, no need to write to the temp file.

+6
source

You have a file with usernames to delete and a file (or stream) of records containing the username. Ideal situation for awk:

 awk ' FNR == NR {user[$1]++; next} !($2 in user) {print} ' users email_users > new_email_users 
+1
source

All Articles