LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Referencing "list" item from environment variable in shell (https://www.linuxquestions.org/questions/linux-newbie-8/referencing-list-item-from-environment-variable-in-shell-924826/)

zx_ 01-20-2012 11:27 AM

Referencing "list" item from environment variable in shell
 
Don't know how much of this is true, but I know I can assign different paths in PATH variable separated by colon ":"

I want to use this feature to split arbitrary string with colon as separator

For example, I assign:

Code:

X=one:two
Now I want to get first item - "one"

How can I reference it in shell, if possible?

I know about some approaches using IFS then looping to get split, but that's not what I'm after, as I need simplest possible form

TIA

zx_ 01-20-2012 11:39 AM

OK, find my way out just after posting.

In sh I can use ${X%:*} and ${X#*:} after assigning X to get split of string with two parts (just like my problem)

For multiple split items perhaps there is some other solution


Cheers

grail 01-20-2012 11:57 AM

You a use the positional variables if they are not already set and you are not worried about overriding them:
Code:

set -- ${X//:/ }

echo $1
echo $2


David the H. 01-21-2012 06:55 AM

There are ever so many ways to split strings; parameter expansions, changing IFS, read, regexes inside [[..]]. Which is best to use really depends on how the line if formatted and what you intend to do with the output. Do you only need the first part, for example, or the ability to access any of the individual parts?

If you only need one part, then parameter expansion is usually the best. For random access of any of the parts, you should use something similar to what grail provided above. I'd usually go with a true array rather than the positional parameters (assuming a shell that supports them), however.

Code:


x="one:two:three"
parts=( ${x//:/ } )

echo "${parts[0]}"
echo "${parts[1]}"
echo "${parts[2]}"

#Another bash variation:

x="one:two:three and a half"
IFS=":" read -a parts <<<"$x"

echo "${parts[0]}"
echo "${parts[1]}"
echo "${parts[2]}"

Notice how the first technique would fail if any of the sub-parts contained whitespace, so changing IFS is safer overall.

See this page for many more string manipulation techniques:

string manipulation


All times are GMT -5. The time now is 11:49 PM.