17
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.

32

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.

14
cut -d ' ' -f 1 < your-file

would be the most efficient.

  • 4
    I noticed this in several of your answers and I was wondering if there's a reason for it: you always seem to add input redirection even when the command can work without it. Can you please explain why the < is useful here? – Joseph R. Nov 5 '13 at 22:38
  • 5
    @JosephR. You mean cut < file vs cut file? Then see unix.stackexchange.com/a/70759/22565 – Stéphane Chazelas Nov 5 '13 at 22:43
  • cut may be the best solution for problems this simple. I would reserve awk (or perl) for more complex matching. – ChuckCottrill Nov 5 '13 at 22:44
  • @StephaneChazelas Thank you for the (characteristic) insight :) – Joseph R. Nov 5 '13 at 22:45
5
awk '{print $1}' file

or

sed 's/ .*//'
1

And the one through perl,

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

Through GNU grep,

$ grep -oP '^[^ ]*' file
bbbbbbbb
ccccccccccccccc
ddddd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.