How to remove line from a file

April 13, 2011 at 06:12:18
Specs: Windows XP
Hi to all!
I've made this script to remove a line from /tmp/passwd file

# BEGIN
echo -n "Insert user: "
read aa
grep -v $aa /tmp/passwd > /tmp/passwd
# END

This doesn't work, because it delete all the entries in my /tmp/passwd file, so after the execution the /tmp/passwd file become empty.
It seems it does not recognize my $aa variable.
How can I do?

thanks


See More: How to remove line from a file

Report •

#1
April 13, 2011 at 08:01:23
Redirecting output to the same file you are greping destroys your file. I suggest you do something like this:

grep -v $aa /tmp/passwd > /tmp/output
mv /tmp/output /tmp/passwd

I have two other comments:

First, you are assuming that the user name is unique. This is not always a good assumption. For example, you could have a valid user: fred. You could also have a valid user fredj. Your grep statement will pick us both of them.

Second, I hope you are not planning on eventually overwriting your original passwd file? If you have root permissions you could do this:

mv /tmp/passwd /etc/passwd

That is really a bad idea.


Report •

#2
April 14, 2011 at 02:38:35
MMM you're right.
So I've to do:

grep -v "^$aa:" /tmp/passwd > /tmp/output
mv /tmp/output /tmp/passwd

because the username in passwd file end with ":"

What do you think about this?


Report •

#3
April 14, 2011 at 02:41:16
This script helps me to manipulate my passwd under a chroot dir: /SFTP/chroot/etc/passwd.
My /etc/passwd file will manipulated only by useradd/userdel/usermod commands.

Thanks in advance!


Report •

Related Solutions

#4
April 14, 2011 at 06:29:18
Ok, it works!

[.......]
line=$(grep "$aa" /SFTP/chroot/etc/passwd)
if [ -n "$line" ]
then
read -ep "Confirm? (y/n) " -sn1
case $REPLY in
y|Y) grep -v "^$aa:" /SFTP/chroot/etc/passwd > /SFTP/chroot/etc/passwd_temp ; mv -f /SFTP/chroot/etc/passwd_temp /SFTP/chroot/etc/passwd ;;
esac
else
printf "%s\n" "User $aa not found " >&2
fi
[.......]


Report •

#5
April 14, 2011 at 10:40:48
Since you asked what I think: I think you have not addressed my question about grep'ing two similar strings: fred fredj

You can do something like this:

I am assuming your passwd file is similar in structure to the /etc/passwd file so the user id is in the first field:

user="nails"
while IFS=":" read user_id restofline
do
   if [  $user_id = $user ]
   then
      echo "do something"
   fi
done < /tmp/passwd


Report •

Ask Question