Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first word of every line with AWK or SED?

Tags:

split

sed

awk

I have a text file like this:

aaaa bbbb cccc
dddd eeee ffff
gggg hhhh iiii
...
..
.

How can I create a text file only with first column of every lines with awk or sed like this?

aaaa
dddd
gggg
...
..
.

I have seen similar topics but I could not resolve my problem!

like image 825
mbzadegan Avatar asked Dec 18 '22 06:12

mbzadegan


2 Answers

If your input is

aaaa bbbb cccc
dddd eeee ffff
gggg hhhh iiii

and what you want is:

aaaa
dddd
gggg

then you can use any of:

awk NF=1       input.file
sed 's/ .*//'  input.file
cut -d' ' -f1  input.file
like image 113
Mischa Avatar answered Dec 22 '22 00:12

Mischa


Using awk: By setting number of fields to 1:

awk '{NF=1}1' inputfile   

Using grep and look arounds:

grep -oP '^.[^ ]+' inputfile

Using sed backrefrencing:

sed -r 's/(^.[^ ]+).*/\1/' inputfile
like image 22
P.... Avatar answered Dec 21 '22 23:12

P....