Skip to main content
added 247 characters in body
Source Link
Stéphane Chazelas
  • 586.9k
  • 96
  • 1.1k
  • 1.7k

Sed

sed 's/\s.*$//'

Grep

grep -o '^\S*'

Awk

awk '{print $1}'

As pointed out in the comments, -o isn't POSIX; however both GNU and BSD have it, so it should work for most people.

Also, \s/\S may not be on all systems, if yours doesn't recognize it you can use a literal space, or if you want space and tab, those in a character classbracket expression ([][...]), or the [[:spaceblank:]] character class (note that strictly speaking \s is equivalent to [[:space:]] and includes vertical spacing characters as well like CR, LF or VT which you probably don't care about).

The awk one assumes the lines don't start with a blank character.

Sed

sed 's/\s.*$//'

Grep

grep -o '^\S*'

Awk

awk '{print $1}'

As pointed out in the comments, -o isn't POSIX; however both GNU and BSD have it, so it should work for most people.

Also, \s/\S may not be on all systems, if yours doesn't recognize it you can use a literal space, or if you want space and tab, those in a character class ([]), or the [[:space:]] character class.

Sed

sed 's/\s.*$//'

Grep

grep -o '^\S*'

Awk

awk '{print $1}'

As pointed out in the comments, -o isn't POSIX; however both GNU and BSD have it, so it should work for most people.

Also, \s/\S may not be on all systems, if yours doesn't recognize it you can use a literal space, or if you want space and tab, those in a bracket expression ([...]), or the [[:blank:]] character class (note that strictly speaking \s is equivalent to [[:space:]] and includes vertical spacing characters as well like CR, LF or VT which you probably don't care about).

The awk one assumes the lines don't start with a blank character.

added 330 characters in body
Source Link
Kevin
  • 41.7k
  • 17
  • 91
  • 113

Sed

sed 's/\s.*$//'

Grep

grep -o '^\S*'

Awk

awk '{print $1}'

As pointed out in the comments, -o isn't POSIX; however both GNU and BSD have it, so it should work for most people.

Also, \s/\S may not be on all systems, if yours doesn't recognize it you can use a literal space, or if you want space and tab, those in a character class ([]), or the [[:space:]] character class.

Sed

sed 's/\s.*$//'

Grep

grep -o '^\S*'

Awk

awk '{print $1}'

Sed

sed 's/\s.*$//'

Grep

grep -o '^\S*'

Awk

awk '{print $1}'

As pointed out in the comments, -o isn't POSIX; however both GNU and BSD have it, so it should work for most people.

Also, \s/\S may not be on all systems, if yours doesn't recognize it you can use a literal space, or if you want space and tab, those in a character class ([]), or the [[:space:]] character class.

Source Link
Kevin
  • 41.7k
  • 17
  • 91
  • 113

Sed

sed 's/\s.*$//'

Grep

grep -o '^\S*'

Awk

awk '{print $1}'