Extracting the second word from a string variable

118,401

Solution 1

Try this way:

y=$(echo $x | awk '{print $2}')
echo $y
  • echo $x display the value of x.
  • awk '{print $2}' prints the second field of the previously displayed x.
  • $(...) hold the output and let assign it to y.

Solution 2

Assuming that there's at least one space before the substring you wish to extract (and that the substring does not contain any spaces), you can do this with a simple parameter expansion:

x="rtcpOnNbActive     true"
y="${x##* }"
echo "[$y]"

output

[true]

Solution 3

It's possible to use bash arrays for that, just place your str inside parenthesis. e.g.:

arr=("first second third")
echo ${arr[1]}

str="first second third"
arr1=($str)
echo ${arr1[1]}

Solution 4

you can use awk:

echo "rtcpOnNbActive         true" | awk '{print $NF}'
true

NF number of field in the current record

using sed:

echo "rtcpOnNbActive         true" | sed 's/.* //g'
true

using string expression:

 a="rtcpOnNbActive         true"
 echo ${a##* }
 true

using grep:

 echo "rtcpOnNbActive         true" | grep -Eo "[a-z]+$"
 true

-o is gives only exact match, [a-z]+ will match letter from a-z and $ means at end

Solution 5

You could use the read built-in

read -r _ y <<<"$x"
printf "%s\n" "$y"
true
Share:
118,401

Related videos on Youtube

Pratibha Jain
Author by

Pratibha Jain

Updated on September 18, 2022

Comments

  • Pratibha Jain
    Pratibha Jain over 1 year

    I have a string "rtcpOnNbActive true" stored in a variable x. I want to extract "true" as substring and store in a variable. How can I do this?

    • PM 2Ring
      PM 2Ring over 9 years
      Will there always be a space in x just before the substring you want to extract?
  • Stéphane Chazelas
    Stéphane Chazelas over 9 years
    echo $x is not display the value of x. printf '%s\n' "$x" would be.
  • Stéphane Chazelas
    Stéphane Chazelas over 9 years
    awk '{print $2}' prints the second field of each line of the previously displayed x.
  • αғsнιη
    αғsнιη over 9 years
    Don't post content of other answer for yours in the same question, please.
  • nyuszika7h
    nyuszika7h over 9 years
    echo is not portable for anything other than a literal string that doesn't start with - and doesn't contain any escape sequences. Its behavior varies even for the bash builtin, depending on how it was compiled, and whether XPG_ECHO is set. Assuming the string contains no escape sequences, this should be fine, but printf '[%s]\n' "$y" is still better.
  • nyuszika7h
    nyuszika7h over 9 years
    echo is not portable for anything other than a literal string that doesn't start with - and doesn't contain any escape sequences. Its behavior varies even for the bash builtin, depending on how it was compiled, and whether XPG_ECHO is set. Also, you should always double quote variable expansions and command substitution (with certain exceptions, where it's not necessary but it doesn't do any harm either). With a string like the OP's, this should be fine, but if you want to make sure printf '%s\n' "${a##* }" would be better.
  • mikeserv
    mikeserv over 9 years
    why involve read? It isn't read that does the split - it is $IFS. For some reason a lot of people consider it ok to split w/ $IFS only when read is involved. You can just do: set -f; IFS=' '; printf %.0s%s $x or whatever. In any case - you need to specify $IFS's value here.
  • Mathias Begert
    Mathias Begert over 9 years
    @mikeserv, it's read doing the splitting using IFS, check the documentation. The main advantage with using read is that it sets variables (which is an OP requirement) and given that it can split strings and populate an array, is good for extracting arbitrary fields from a string. Additionally, I am assuming default IFS here, but it's easy enough to set if needed, IFS=$' \n\t' read -r _ y <<<"$x" will do the trick
  • Mathias Begert
    Mathias Begert over 9 years
    @mikeserv, you're off my Christmas card list.
  • PM 2Ring
    PM 2Ring over 9 years
    @nyuszika7h: Good point, and after having read Stéphane Chazelas say similar things here and in other recent questions I really ought to break my habit of using echo to display the value of variables, even in "throw-away" examples like this.
  • mikeserv
    mikeserv over 9 years
    bah humbug. xmas is for suckers.
  • prashant thakre
    prashant thakre about 3 years
    This is the best approach thanks its very simple and not an errorpron.
  • Cecil Curry
    Cecil Curry about 2 years
    The only sane solution. Every other solution either invokes external third-party commands that may not necessarily be available or behave as expected under the current platform (e.g., awk) or performs fragile string-munging guaranteed to fail in obvious corner cases (e.g., echo "${x##* }").