Reputation: 43518
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?
Upvotes: 38
Views: 107590
Reputation: 81
...or on Windows (if you have GnuWin32 grep) :
grep -Eo "^[^ ]+" file
Upvotes: 0
Reputation: 6623
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]
Upvotes: 2
Reputation: 38436
You can use awk
:
awk '{print $1}' your_file
This will "print" the first column ($1
) in your_file
.
Upvotes: 53
Reputation: 185126
try doing this with coreutils cut
:
cut -d' ' -f1 file
Upvotes: 18
Reputation: 3402
I see there are already answers. But you can also do this with sed:
sed 's/ .*//' fileName
Upvotes: 4