user2871860
user2871860

Reputation: 23

How can I get sed to only match to the first occurrence of a character?

I'm using GNU Sed 4.2.1. I'm trying to replace the second field in the following line (the password in /etc/shadow). Awk is not an option.

username:P@s$w0rDh@$H:15986:0:365::::

I've tried

sed -i 's/\(^[a-z]*\):.*?:/\1:TEST:/'

but nothing. I've tried many variations but for some reason I can't get it to only match that field. Help?

Upvotes: 2

Views: 14531

Answers (2)

anubhava
anubhava

Reputation: 786091

Using sed:

sed -i.bak 's/^\([^:]*:\)[^:]*\(.*\)$/\1foo\2/' file

Using awk you can do:

awk -F: '{$2="foo"}1' OFS=: file

Upvotes: 1

nosid
nosid

Reputation: 50124

Use [^:]* to match everything up until the next :

sed -i 's/^\([^:]*\):\([^:]*\):/\1:TEST:/'

Upvotes: 7

Related Questions