How to remove a given line from a file
I'm writing a BASH script to integrate our company's custom intranet with our postfix email server. In one situation, the script mu开发者_运维知识库st delete a line from the postfix virtual file which takes on the following form (for the most part): emailAddress username.
xyx@abc.com xyz tuv@abc.com tuv lmn@abc.com 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" != "$usr@abc.com $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.
Try sed with -i, like:
sed -i -e "/^$usr@abc.com/d" virtual
that should remove the line from virtual, no need to write to a temp file.
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
精彩评论