
我有一個字串:
one_two_three_four_five
我需要保存變A
數值和上面字串中的two
變B
數值four
我正在使用 ksh。
答案1
使用cut
with_
作為欄位分隔符號並取得所需的欄位:
A="$(cut -d'_' -f2 <<<'one_two_three_four_five')"
B="$(cut -d'_' -f4 <<<'one_two_three_four_five')"
您也可以使用echo
and 管道代替此處的字串:
A="$(echo 'one_two_three_four_five' | cut -d'_' -f2)"
B="$(echo 'one_two_three_four_five' | cut -d'_' -f4)"
例子:
$ s='one_two_three_four_five'
$ A="$(cut -d'_' -f2 <<<"$s")"
$ echo "$A"
two
$ B="$(cut -d'_' -f4 <<<"$s")"
$ echo "$B"
four
請注意,如果$s
包含換行符,則將返回一個多行字串,其中包含 的每行中的第二個/第四個字段,而不是$s
中的第二個/第四個字段$s
。
答案2
想看awk
答案,所以這裡有一個:
A=$(awk -F_ '{print $2}' <<< 'one_two_three_four_five')
B=$(awk -F_ '{print $4}' <<< 'one_two_three_four_five')
答案3
僅使用 POSIX sh 構造,您可以使用參數替換結構一次解析一個分隔符號。請注意,此程式碼假定存在必要數量的字段,否則最後一個字段將重複。
string='one_two_three_four_five'
remainder="$string"
first="${remainder%%_*}"; remainder="${remainder#*_}"
second="${remainder%%_*}"; remainder="${remainder#*_}"
third="${remainder%%_*}"; remainder="${remainder#*_}"
fourth="${remainder%%_*}"; remainder="${remainder#*_}"
或者,您可以使用不含引號的參數替換通配符擴充殘疾人士和IFS
設定為分隔符(僅當分隔符號是單一非空白字元或任何空白序列是分隔符號時才有效)。
string='one_two_three_four_five'
set -f; IFS='_'
set -- $string
second=$2; fourth=$4
set +f; unset IFS
這會破壞位置參數。如果在函數中執行此操作,則只有函數的位置參數受到影響。
對於不包含換行符的字串,另一種方法是使用read
內建函數。
IFS=_ read -r first second third fourth trail <<'EOF'
one_two_three_four_five
EOF
答案4
您zsh
可以將字串( on _
)拆分為陣列:
non_empty_elements=(${(s:_:)string})
all_elements=("${(@s:_:)string}")
然後透過數組索引存取每個/任何元素:
print -r -- ${all_elements[4]}
請記住zsh
(與大多數其他 shell 一樣,但與ksh
/不同bash
)數組索引從 1 開始。
或直接在一個擴充中:
print -r -- "${${(@s:_:)string}[4]}"
或使用匿名函數使其元素在其$1
, $2
... 中可用:
(){print -r -- $4} "${(@s:_:)string}"