Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a given line from a file

Tags:

bash

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.

like image 306
Reece Avatar asked Feb 24 '23 05:02

Reece


1 Answers

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.

like image 191
Steve Kehlet Avatar answered Mar 04 '23 09:03

Steve Kehlet