【问题标题】:Linux bash; manipulate PATH type varLinux 重击;操作 PATH 类型 var
【发布时间】:2021-02-26 12:55:34
【问题描述】:

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 替换备忘单,但令人难以置信。 sed 也是一种方式,但我似乎永远无法摆脱分隔符。

我确实做到了这一点

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

这不是很远,但至少我得到了 Y,但它对 X 没有任何作用。老实说,我还是不明白它们,只是使用了备忘单。因此,我们将不胜感激提供解决方案的解释。

【问题讨论】:

标签: bash shell variable-substitution


【解决方案1】:

你可以:

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 readbash manualPOSIX 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 并分配一个array。使用${arr[0] 提取第一个元素。 arr[*] 使用 IFS 中的第一个字符连接数组元素,并使用 ${ :1} 扩展提取除第一个之外的所有元素,请参阅shell parameter expansions

【讨论】:

  • 谢谢。这完成了工作,
【解决方案2】:

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

#!/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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2018-02-14
    • 2016-09-10
    相关资源
    最近更新 更多