Benedict Lewis
Benedict Lewis

Reputation: 2813

Remove line from text file given first word

I have a file of usernames and password for a VPN site I'm making. It looks something like this:

#user   #server    #password   #ip
user1   server1    pass1       *
user2   server4    pass67      *
user3   server8    pass32      someip
user9   server1    62pass      *

If I have written a simple shell script to append a user to the table, and restart the VPN process:

#!/bin/sh
echo "Adding user $1 with password $2."
echo "$1 l2tpd $2 *" >> /etc/ppp/chap-secrets
echo "Restarting xl2tpd process."
sudo /etc/init.d/xl2tpd restart
echo "VPN restarted, user added."

Now what I want to do is write a script that allows me to delete a user from the table, and then restart the process. In order to do this, I have to pass one argument, the username.

How do I lookup the line with that username, and then delete it?

Upvotes: 0

Views: 188

Answers (3)

devnull
devnull

Reputation: 123508

You could use sed:

sed '/^user1/d' filename

would remove the line starting with user1. For saving the changes to the file in-place, use the -i option.

In order to use a variable, ensure that you use double quotes:

sed "/^$1/d" filename

Alternatively, you might use grep:

grep -v "^$1" filename

Upvotes: 2

ghoti
ghoti

Reputation: 46856

While a basic sed script like devnull's may do the trick, you should be aware that sed searches for a regular expression, not a string, and his solution suggests using raw command line content as part of the sed command.

I wouldn't do this. Input validation is important, because even if no nasty people will gain access to your shell, typos do happen. For example:

#!/bin/bash

if [[ "$1" ~ ^[a-z][a-z0-9]*$ ]]; then
  if sed -i.bak -e "/^$1 /d" /etc/ppp/chap-secrets; then
    echo "delete user $1"
  fi
else
  echo "ERROR: Invalid characters.  Please try again." >&2
  exit 1
fi

Note that we're testing to make sure that users follow a safe format with no special characters, and we're also making sure that deleting user "foo" doesn't also delete user "foobar" by putting a space after the $1 in range in the sed script.

I recommend keeping the -i.bak in there in case something untoward happens.

Upvotes: 1

BMW
BMW

Reputation: 45243

if you have gnu sed with -i option.

#!/bin/sh
echo "deleting user $1."
sed -i "/^$1/d" /etc/ppp/chap-secrets
echo "Restarting xl2tpd process."
sudo /etc/init.d/xl2tpd restart
echo "VPN restarted, user deleted."

If not, replace the sed -i command with below commands:

sed "/^$1/d" /etc/ppp/chap-secrets > temp
mv temp /etc/ppp/chap-secrets

Upvotes: 0

Related Questions