Nth word in a string variable

前端 未结 6 1496
夕颜
夕颜 2020-12-13 08:05

In Bash, I want to get the Nth word of a string hold by a variable.

For instance:

STRING=\"one two three four\"
N=3

Result:

相关标签:
6条回答
  • 2020-12-13 08:25

    No expensive forks, no pipes, no bashisms:

    $ set -- $STRING
    $ eval echo \${$N}
    three
    

    But beware of globbing.

    0 讨论(0)
  • 2020-12-13 08:29
    echo $STRING | cut -d " " -f $N
    
    0 讨论(0)
  • 2020-12-13 08:39

    A file containing some statements :

    cat test.txt
    

    Result :

    This is the 1st Statement
    This is the 2nd Statement
    This is the 3rd Statement
    This is the 4th Statement
    This is the 5th Statement
    

    So, to print the 4th word of this statement type :

    cat test.txt |awk '{print $4}'
    

    Output :

    1st
    2nd
    3rd
    4th
    5th
    
    0 讨论(0)
  • 2020-12-13 08:41

    An alternative

    N=3
    STRING="one two three four"
    
    arr=($STRING)
    echo ${arr[N-1]}
    
    0 讨论(0)
  • 2020-12-13 08:41

    Using awk

    echo $STRING | awk -v N=$N '{print $N}'
    

    Test

    % N=3
    % STRING="one two three four"
    % echo $STRING | awk -v N=$N '{print $N}'
    three
    
    0 讨论(0)
  • 2020-12-13 08:49
    STRING=(one two three four)
    echo "${STRING[n]}"
    
    0 讨论(0)
提交回复
热议问题