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 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 |
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 |
You a use the positional variables if they are not already set and you are not worried about overriding them:
Code:
set -- ${X//:/ } |
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:
See this page for many more string manipulation techniques: string manipulation |
All times are GMT -5. The time now is 11:49 PM. |