Michael
Michael

Reputation: 174

Select and replace string from first occurence of defined character till last occurence

I want print usernames and real names from /etc/passwd in this format: johnwick3=John Wick

The entries in /etc/passwd looks like this:

johnwick3:x:15905:10513:John Wick:/home/john/folder:/bin/bash

The numbers are different on every line.

So I extracted everything till the end of name with:

cat /etc/passwd | grep -o -P '(?<=).*(?=:/home)'

which gives me:

johnwick3:x:15905:10513:John Wick

How can I extract everything between first colon till last colon and replace it with "=" ?

Upvotes: 0

Views: 37

Answers (1)

KamilCuk
KamilCuk

Reputation: 141010

The following should be just enough for some displaying:

grep '/home' /etc/passwd | cut -d: -f1,5 | tr ':' '='

But in a script I would:

awk -F: -v OFS== '$6 ~ "^/home/"{print $1,$5}' /etc/passwd

Upvotes: 2

Related Questions