33

I have a file containing many lines, and I want to display only the first word of each line with the Linux commands.

How can I do that?

GKFX
  • 1,386
  • 1
  • 11
  • 30
MOHAMED
  • 41,599
  • 58
  • 163
  • 268

6 Answers6

49

You can use awk:

awk '{print $1}' your_file

This will "print" the first column ($1) in your_file.

newfurniturey
  • 37,556
  • 9
  • 94
  • 102
  • post edited, why giving wrong solution when you give the good one at the same time ? It was a useless use of cat : http://partmaps.org/era/unix/award.html#cat – Gilles Quénot Mar 15 '13 at 14:22
  • He specified `cat` in his question; figured I'd at least show how to use it in a piped-command (but I did mention it was overkill for this purpose =P). – newfurniturey Mar 15 '13 at 14:24
44

Try doing this using :

grep -Eo '^[^ ]+' file
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
16

try doing this with coreutils cut :

cut -d' ' -f1 file
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
4

I see there are already answers. But you can also do this with sed:

sed 's/ .*//' fileName
Memento Mori
  • 3,327
  • 2
  • 22
  • 29
2

The above solutions seem to fit your specific case. For a more general application of your question, consider that words are generally defined as being separated by whitespace, but not necessarily space characters specifically. Columns in your file may be tab-separated, for example, or even separated by a mixture of tabs and spaces.

The previous examples are all useful for finding space-separated words, while only the awk example also finds words separated by other whitespace characters (and in fact this turns out to be rather difficult to do uniformly across various sed/grep versions). You may also want to explicitly skip empty lines, by amending the awk statement thus:

awk '{if ($1 !="") print $1}' your_file

If you are also concerned about the possibility of empty fields, i.e., lines that begin with whitespace, then a more robust solution would be in order. I'm not adept enough with awk to produce a one-liner for such cases, but a short python script that does the trick might look like:

>>> import re
>>> for line in open('your_file'):
...     words = re.split(r'\s', line)
...     if words and words[0]:
...         print words[0]
Jeffrey Froman
  • 6,113
  • 1
  • 16
  • 11
  • Actually perl regex is widely available in _grep_, and `\s` comes conveniently to the rescue: `grep -Po '^\s*\K\S+' …` – bobbogo Jan 09 '17 at 14:48
0

...or on Windows (if you have GnuWin32 grep) :

grep -Eo "^[^ ]+" file
user3038458
  • 81
  • 1
  • 4