I am having a variable which shows on echo like this

$ echo $var
129 148

I have to take only 129 as output. How will I split 129 and 148?


In addition to jasonwryan's suggestion, you can use cut:

echo $var | cut -d' ' -f1

The above cuts the echo output with a space delimiter (-d ' ') and outputs the first field (-f1)

| improve this answer | |
  • it is not working. i already used it. it says command not found. – surbhi Mar 19 '15 at 6:56
  • 4
    @surbhi What says command not found? cut is a standard utility. Your script probably has an error somewhere else. More generally, never say “it is not working”. Always say exactly what code you ran, exactly what happened, and copy-paste error messages. – Gilles 'SO- stop being evil' Mar 19 '15 at 22:48
  • This answer should be accepted, as it's the most concise and direct way. It won't work in cases that are more complicated than the given example, of course. – Dan Nguyen Jan 5 '17 at 14:56

A neat way to do this is to use a bash array to split up a string on spaces. You can declare an array simply by using brackets:

var="129 148     181"
vars=( $var )
echo "First  word of var: '${vars[0]}'"
echo "Second word of var: '${vars[1]}'"
echo "Third  word of var: '${vars[2]}'"
echo "Number of words in var: '${#vars[@]}'"
| improve this answer | |
  • this says command not found – surbhi Mar 19 '15 at 6:58
  • It depends on you using bash. If you are using a different shell it may not work. echo $SHELL should show: /bin/bash or similar. – gogoud Mar 19 '15 at 7:01
  • doesn't work in zsh ;( – TonyH Aug 22 '19 at 14:12
  • This does work in ZSH zoom="one two three"; declare -a zoomie=( $( echo $zoom | cut -d' ' -f1- ) ); echo ${zoomie[2]}; – TonyH Aug 22 '19 at 14:17

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.