34
aaaaaaaa 09  
bbbbbbbb 90   
ccccccccccccccc  89  
ddddd 09

Using sed/awk/replace, in the above text I want to remove anything that comes after the first space in each line. For example the output will be:

aaaaaaaa  
bbbbbbbb    
ccccccccccccccc  
ddddd 

any help will be appreciated.

jlliagre
  • 61,204
Rana Khan
  • 921

4 Answers4

49

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.

Kevin
  • 40,767
19
cut -d ' ' -f 1 < your-file

would be the most efficient.

  • cut may be the best solution for problems this simple. I would reserve awk (or perl) for more complex matching. – ChuckCottrill Nov 05 '13 at 22:44
  • @StéphaneChazelas Looking at the man-page for cut, I can't tell if it will accept any sort of regex syntax. Do you have any idea whether or not it will, and if so, which type(s)? sry to bother and thanks. – Nate T Sep 18 '21 at 13:40
  • @NateT, no only single characters and with several implementations, even limited to singe byte characters only. – Stéphane Chazelas Sep 18 '21 at 16:02
6
awk '{print $1}' file

or

sed 's/ .*//'
mikeserv
  • 58,310
jlliagre
  • 61,204
1

And the one through perl,

$ perl -pe 's/^([^ ]+) .*$/\1/' file
aaaaaaaa
bbbbbbbb
ccccccccccccccc
ddddd

Through GNU grep,

$ grep -oP '^[^ ]*' file
bbbbbbbb
ccccccccccccccc
ddddd
Avinash Raj
  • 3,703