Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Here is a LIST:

List = "abcd 1234 jvm something"

How to get the second element "1234" without looping all the list?

share|improve this question

2 Answers 2

up vote 15 down vote accepted

no spaces between equal sign

$ List="abcd 1234 jvm something"
$ set -- $List
$ echo $2
1234

Some other ways, although not as efficient as using shell's internals

$ echo $List | cut -d" " -f2
1234
$  echo $List | awk '{print $2}'
1234
$ echo $List | sed 's/^.[^ \t]* //;s/ .*//'
1234
$ echo $List | tr " " "\n"|sed -n '2p'
1234
share|improve this answer
    
Thanks.would you give some comments in the code please? –  SpawnST Mar 19 '10 at 3:32
    
I mean the second line. –  SpawnST Mar 19 '10 at 3:32
8  
@Spawn set -- $something splits $something at the $IFS character (by default space) and assigns the split parts to the positional variables $1,$2,... –  Benjamin Bannier Mar 19 '10 at 3:44
    
@honk:Thank you:-) –  SpawnST Mar 19 '10 at 3:46

Just to supplement ghostdog's answer: you could also put $List's elements into an array and access the specific list element from there

List="abcd 1234 jvm something"
arr=($List)
echo ${arr[1]}

Note that the array indices are counted 0,1,2,... .

This has the advantage of not polluting the shell environment with too many new variables.

share|improve this answer
    
That's nice.:-) –  SpawnST Mar 19 '10 at 4:45
1  
no need to echo: arr=($List) –  user31894 Mar 19 '10 at 5:19
    
@ghostdog probably compulsive behavior, edited. –  Benjamin Bannier Mar 19 '10 at 5:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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