pattern match and replace another pattern in same line

I have a pattern

username:x:32005:32006::/usr/local/user:/bin/bash

I need to match the line containing username and replace /bin/bash with /usr/local/my/bin/noshell

So it becomes

username:x:32005:32006::/usr/local/user:/usr/local/my/bin/noshell

This will print all lines, but first modify the shell field if the username matches username.

awk -v FS=: -v OFS=: -v USER="username" '$1==USER { $7="/usr/local/my/bin/noshell" } 1' < input > output

# CHECK THE OUTPUT FIRST before overwriting your input!
# You don't want to mangle /etc/passwd by accident.
# Also, overwrite it, don't do mv output input.  
# Changing /etc/passwd's ownership or permissions would be bad.
cat output > input

It comes as follows.

user:x:32008:32011::/home/user:/bin/bash:/usr/local/my/bin/noshell

Did you outrun my edit? I briefly posted it with $8 when it was supposed to be $7, which would do exactly that.

I also modified it so you can pass in the username more easily.

1 Like

This worked

# grep username /etc/passwd | sed 's/\/bin\/bash/\/sbin\/nologin/'
username:x:32008:32011::/home/user:/sbin/nologin

---------- Post updated 11-19-11 at 12:01 AM ---------- Previous update was 11-18-11 at 11:59 PM ----------

Corona688

Just checked your modified stuff. It works well. Thanks :slight_smile:

Using sed alone...

sed -i '/^username/{s!/bin/bash!/sbin/nologin!g}' /etc/passwd

This will modify the file /etc/passwd... so be careful... You can test it out first by removing -i option...

--ahamed

Not trustworthy. What if they just happen to have username in their comment field, home directory, or path?

Yes you are right. The one you gave works flawlessly.