Joe E
Joe E

Reputation: 85

linux bash, print line contaning string in a column

let's say my file /etc/passwd contains

ntp:x:38:40::/etc/ntp:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
haldaemon:x:38:68:HAL daemon:/:/sbin/nologin
pulse:x:497:495:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin
gdm:x:42:38::/var/lib/gdm:/sbin/nologin
sshd:x:388:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
tcpdump:x:38:72::/:/sbin/nologin

what i'm trying to do is print the line containing a "38" in the third column, something which will print this:

ntp:x:38:40::/etc/ntp:/sbin/nologin haldaemon:x:38:68:HAL daemon:/:/sbin/nologin gdm:x:42:38::/var/lib/gdm:/sbin/nologin tcpdump:x:38:72::/:/sbin/nologin

I tried something like

cat "/etc/passwd" | cut -d ":" -f3 | grep "38"

but it only show the "38" not the entire line

Thanks

Upvotes: 2

Views: 1068

Answers (6)

abasu
abasu

Reputation: 2524

only sed was remaining :)

sed -n '/^[^:]*:[^:]:*38:/p' /etc/passwd

Upvotes: 0

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17188

You could use grep

grep ^.*:.*:38:  /etc/passwd

Improved version after tripleee's comment:

egrep ^[^:]*:[^:]*:38: /etc/passwd

Upvotes: 2

Fredrik Pihl
Fredrik Pihl

Reputation: 45662

In pure bash (awk is the way to go though!):

$ while read line; do array=(${line//:/ }); [ ${array[2]} -eq 38 ] && echo $line; done < input
ntp:x:38:40::/etc/ntp:/sbin/nologin
haldaemon:x:38:68:HAL daemon:/:/sbin/nologin

Upvotes: 1

CaWal
CaWal

Reputation: 21

You can do this:

cat /etc/passwd  | egrep "^[[:alnum:]]*:[[:alnum:]]*:38:.*"

Using the alphanumeric character class.

Upvotes: 1

Kent
Kent

Reputation: 195079

you may test this:

awk -F: '$3~/38/' /etc/passwd

note that 3rd column with 338 or 838 will be printed as well.

Upvotes: 3

P.P
P.P

Reputation: 121397

You can use wk:

awk -F: '$3==38{print}' file

In general, I would suggest you avoid parsing /etc/passwd directly. Instead you can use getent passwdto read the passwd database.

Upvotes: 2

Related Questions