7

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!

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
mbzadegan
  • 71
  • 1
  • 1
  • 4
  • 2
    Possible duplicate of [Printing only the first field in a string](https://stackoverflow.com/questions/15024561/printing-only-the-first-field-in-a-string) – Sundeep Jul 03 '17 at 03:59
  • Possible duplicate of [How to get the first column of every line from a CSV file?](https://stackoverflow.com/questions/11668621/how-to-get-the-first-column-of-every-line-from-a-csv-file) or https://stackoverflow.com/questions/19959746/extracting-columns-space-or-tab-delimited-from-text-file-in-linux or https://stackoverflow.com/questions/8299553/how-to-get-the-first-column-of-comm-output – Jedi Jul 03 '17 at 03:59

2 Answers2

10

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
halfer
  • 19,824
  • 17
  • 99
  • 186
Mischa
  • 2,240
  • 20
  • 18
3

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
P....
  • 17,421
  • 2
  • 32
  • 52
  • Why the "." at the start of the sed and grep patterns? – Mischa Apr 28 '18 at 22:13
  • @mischa , here dot means any character so ^. Means line start followed by any character. – P.... Apr 29 '18 at 08:04
  • Yes, I know "what" it means; I was puzzled "why" you had it. For the example input, it is redundant. For input that permits a one-character first field, it fails.I'm sure you had a a reason ... but what? – Mischa May 01 '18 at 04:30