Reputation: 53
I'm writing a BASH script to integrate our company's custom intranet with our postfix email server. In one situation, the script must delete a line from the postfix virtual file which takes on the following form (for the most part): emailAddress username.
[email protected] xyz [email protected] tuv [email protected] lmn
my bash script needs to read through a file that contains user names (one on every line) and delete the corresponding line from the virtual file. So lets say it reads a line containing the username xyz; thus in the example below the variable $usr
is storing the value 'xyz'
.
touch virtual.tmp
cat virtual | while read LINE ; do
if [ "$LINE" != "[email protected] $usr" ] ; then
echo "$LINE" >> virtual.tmp
fi
done
rm -rf virtual
mv virtual.tmp virtual
However this code doesn't work and it is probably not efficient, as all I want to do is delete a line based off of a username. Presumably I might not have to read the whole file.
Upvotes: 4
Views: 345
Reputation: 246799
You have a file of usernames to delete, and a file (or stream) of records containing the username. Perfect situation for awk:
awk '
FNR == NR {user[$1]++; next}
!($2 in user) {print}
' users email_users > new_email_users
Upvotes: 1
Reputation: 6426
Try sed with -i, like:
sed -i -e "/^[email protected]/d" virtual
that should remove the line from virtual, no need to write to a temp file.
Upvotes: 7