Getting the first word using sed,awk or perl

Input:

root:x:0:
daemon:x:1:
bin:x:2:
sys:x:3:
adm:x:4:
tty:x:5:
disk:x:6:
lp:x:7:
mail:x:8:

Output:

root
daemon
bin
sys
adm
tty
disk
lp
mail
sed "s/:.*//"
1 Like
awk -F: '{print $1}' infile
1 Like

Shorter one :wink:

awk -F: '$0=$1' file

or

cut -d: -f1 file
1 Like
perl -F: -lane 'print $F[0]'  infile
# sed 's/\([^:]*\).*/\1/' infile
root
daemon
bin
sys
adm
tty
disk
lp
mail
while IFS=":" read -r c1 c2
do
  echo "$c1"
done < myfile

And a few more in Perl:

$
$
$ cat f6
root:x:0:
daemon:x:1:
bin:x:2:
$
$
$ perl -plne '$_=substr($_,0,index($_,":"))' f6
root
daemon
bin
$
$
$ perl -plne 's/^(.*?):.*/$1/' f6
root
daemon
bin
$
$
$ perl -plne 's/:.*//' f6
root
daemon
bin
$
$

tyler_durden

in ksh:

cut -d':' -f1 /path/to/file

-d':' : delimiter character, used to separate the "fields"
-f<number> : which fields should be displayed, accepts numbers, lists of numbers (i.e. "1,2,4,7,") and ranges ("1-3,4,8-9").

I hope this helps.

bakunin