In Bash, voglio ottenere l'ennesima parola di una stringa trattenuta da una variabile.
Per esempio:
STRING="one two three four"
N=3
Risultato:
"three"
Quale comando / script Bash potrebbe fare questo?
In Bash, voglio ottenere l'ennesima parola di una stringa trattenuta da una variabile.
Per esempio:
STRING="one two three four"
N=3
Risultato:
"three"
Quale comando / script Bash potrebbe fare questo?
Risposte:
echo $STRING | cut -d " " -f $N
Un'alternativa
N=3
STRING="one two three four"
arr=($STRING)
echo ${arr[N-1]}
IFS(il separatore di campo interno) su ":" o qualcosa al posto dello spazio bianco, modificalo prima di provare questo.
Un file contenente alcune dichiarazioni:
cat test.txt
Risultato:
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
Quindi, per stampare la quarta parola di questo tipo di istruzione:
cat test.txt |awk '{print $4}'
Produzione :
1st
2nd
3rd
4th
5th
STRING=(one two three four)
echo "${STRING[n]}"