Linux bash;操作 PATH 类型变量

Linux bash; manipulate PATH type var

Linux debian bash。 我有一个要操作的 PATH 类型变量 'X'。 'X' 可以是由“:”分隔的任意数量的元素 例如,使用水果:

set X=apple:pear:orange:cherry

我如何提取第一个元素减去它的分隔符,将它保存到一个新变量 'Y',然后从 'X' 中删除它和它的分隔符。如..

apple:pear:orange:cherry

变成

Y=apple X=pear:orange:cherry

我看过 bash 替换作弊 sheet,但令人难以置信。 Sed 也是一种方法,但我似乎永远无法摆脱分隔符。

我确实做到了这一点

IFS=: arr=($X)
Y=${arr[0]}
cnt=${#arr[@]}
IFS=

这不是很远,但至少我得到了 Y,但它对 X 没有任何作用。老实说,我反正不理解它们,只是使用了作弊 sheet。因此,将不胜感激对解决方案的解释。

你可以:

X=apple:pear:orange:cherry
IFS=: read -r Y X <<<"$X"    # note - will fail with newlines
declare -p Y X
# declare -- Y="apple"
# declare -- X="pear:orange:cherry"

read 会将第一个元素分配给 Y,然后将其余元素分配给 X。有关详细信息,请参阅 read 和您的 shell 的文档,尤其是 man 1p read and bash manual and POSIX read.

但是使用带拆分的数组也可以。有趣的事实 - 它可以是一行。

X=apple:pear:orange:cherry
IFS=:
arr=($X)
Y=${arr[0]}
X="${arr[*]:1}"
declare -p Y X
# declare -- Y="apple"
# declare -- X="pear:orange:cherry"

($X) 会做 word splitting expansion and assign an array. With ${arr[0] the first element is extracted. The arr[*] joins the array elements using first character in IFS and using ${ :1} expansion all elements except the first are extracted, see shell parameter expansions

您可以将以冒号分隔的字符串拆分成一个数组,对其进行操作,然后重建一个新字符串:

#!/usr/bin/env bash

x=apple:pear:orange:cherry

echo "x is $x"


IFS=:
# Split x up into an array using the value of IFS as the delimiter.
read -r -a xarr <<< "$x"
# Assign the first element to y
y=${xarr[0]}
# And remove it from the array.
unset "xarr[0]"
# Rebuild x without the first element.
x="${xarr[*]}"
unset -v IFS

echo "y is $y and x is now $x"