Need to replace last field in a file,if first field matches

Hi,

Need to replace last field in a file(/etc/passwd) ,if first filed matches with particular username.

Scenario:

cat testfor1
deekshi:x:7082:7082::/home/deekshi:/bin/bash
harini1:x:7083:7083::/home/harini1:/bin/bash

Here,if first field contains "deekshi", then i should replace /bin/bash with /bin/nologin

Expected Output:

cat testfor1
deekshi:x:7082:7082::/home/deekshi:/bin/nologin
harini1:x:7083:7083::/home/harini1:/bin/bash

As of now i tried like below,

sed '/deekshi/s|$|/bin/nologin|' testfor1

But its not working

TIA

DON'T mess around manually with important system files (like /etc/passwd), as this thread may teach. And even less so do automatic mass changes with scripts... Use the respective system provided tools, e.g. usermod.

If you do, you should know EXACTLY what you are doing and how to reverse possibly wrong-going modifications.

1 Like

Howsoever, "But its not working" is not an utmost good starting point for an analysis. You should describe exactly what in the current behaviour doesn't fulfill your needs or what the error message(s) be.

I guess the target string is appended to the entry, not replacing the last field's value? So you should provide that value, so the s ubstitute has something to replace:

sed '/^deekshi/s|[^:]*$|/bin/nologin|' file
deekshi:x:7082:7082::/home/deekshi:/bin/nologin
harini1:x:7083:7083::/home/harini1:/bin/bash

On top, it is good practice to anchor the search pattern (if possible), here to the start-of-line, to be safe of false positives.

Do not use sed to modify /etc/passwd or any important system file. Why? Because other files you do not know about may also need changes.

In Linux to lock an acount:

usermod -L  username
passwd -l  username

For /etc/password , please use chsh or usermod

i.e

usermod -s /sbin/nologin deekshi
chsh -s /sbin/nologin deekshi

Notice: In Linux the path is, quite often, /sbin/nologin . You can check the shells available with:

chsh -l

For testfor1

perl -palF':' -e '/deekshi/ and s|$F[-1]|/bin/nologin|' testfor1