0

It is my understanding that when writing a Unix shell program you can iterate through a string like a list with a for loop. Does this mean you can access elements of the string by their index as well?

For example:

foo="fruit vegetable bread"

How could I access the first word of this sentence? I've tried using brackets like the C-based languages to no avail, and solutions I've read online require regular expressions, which I would like to avoid for now.

4

2 に答える 2

2

$foo関数に引数として渡します。などを使用$1$2て、関数内の対応する単語にアクセスできます。

function try {
 echo $1
}

a="one two three"

try $a

編集:別のより良いバージョンは次のとおりです:

a="one two three"
b=( $a )
echo ${b[0]}

EDIT(2):このスレッドを見てください。

于 2013-01-23T16:27:02.800 に答える
0

配列を使用することが最善の解決策です。

間接変数を使用したトリッキーな方法は次のとおりです

get() { local idx=${!#}; echo "${!idx}"; }

foo="one two three"

get $foo 1  # one
get $foo 2  # two
get $foo 3  # three

ノート:

  • $#関数に与えられたパラメータの数 (これらすべての場合で 4)
  • ${!#}最後のパラメータの値です
  • ${!idx}は' 番目のパラメータのですidx
  • $fooシェルが文字列を単語に分割できるように、引用符は使用しないでください。

少しエラーチェックを行います:

get() {
  local idx=${!#}
  if (( $idx < 1 || $idx >= $# )); then
    echo "index out of bounds" >&2
    return 1
  fi
  echo "${!idx}"
}

この機能は実際には使用しないでください。配列を使用します。

于 2013-01-24T04:23:41.373 に答える