Suppose, the result of a command in linux shell is as follows:
X and Y are friends
Is there any way to slice each of the words (X, and, Y, are, friends) or the first n words from the result, so that they can be used for different operations?
Suppose, the result of a command in linux shell is as follows:
Is there any way to slice each of the words (X, and, Y, are, friends) or the first n words from the result, so that they can be used for different operations? |
||||
|
There are two main ways to capture the output of a command in a shell script: command substitution and the The simple way to split the output into words is to rely on the shell's built-in splitting feature, and put the output into an array:
This works in shells with arrays: ksh93¹, mksh, bash, zsh. In other shells, you can't store a list of words except in the positional parameters.
Actually, each word in the output is treated as a wildcard pattern, and replaced by the list of matching files if any. (Except in zsh, which only does this when explicitly instructed unless in sh compatibility mode.) For example, if one of the words is
With
Alternatively, in ksh93, bash or zsh, you can pass the input in a process substitution.
If you want to store the words in an array, you can use
is equivalent to
if the command outputs a single line, except that it doesn't reset the ¹ Ksh88 has arrays but assignment uses a different syntax. |
|||
|
With
Assuming the default the default value of IFS, that will split on sequences blanks (space, tab, newline), or NULs. You can make it:
For those 5 words to be in |
|||
|
You can also di this directly in the shell using
The default delimiter is whitespace but you can set it to something else by changing the
|
|||
|
How about
The I've place the string in a variable in the example above, but you could pipe from the output of a command:
|
|||
|