Bash从变量中删除带有特殊字符的String

问题描述 投票:0回答:1

我需要从变量中删除带有特殊字符的字符串,

我有这个字符串,这是一个我想从一个更大的路径中删除的路径,我存储在一个变量中。

那些是参数:

FULL_PATH=Server/.*/resources/schema/v12_55_6/.*/.*-dbSchemaDescriptor.xml,Server/.*/resources/SpringIOC/dataupgrader/v12_55_6/.*/.*-dataUpgrader.xml,Server/.*/java/com/company/mqm/dataupgrader/v12_55_6/.*/.*.java,Server/.*/resources/indexes/v12_55_6/.*.index,Server/.*/resources/schema/v12_55_7/.*/.*-dbSchemaDescriptor.xml,Server/.*/resources/SpringIOC/dataupgrader/v12_55_7/.*/.*-dataUpgrader.xml,Server/.*/java/com/company/mqm/dataupgrader/v12_55_7/.*/.*.java,Server/.*/resources/indexes/v12_55_7/.*.index,Server/.*/resources/schema/v12_55_8/.*/.*-dbSchemaDescriptor.xml,Server/.*/resources/SpringIOC/dataupgrader/v12_55_8/.*/.*-dataUpgrader.xml,Server/.*/java/com/company/mqm/dataupgrader/v12_55_8/.*/.*.java,Server/.*/resources/indexes/v12_55_8/.*.index

这是我想从变量中删除的路径(让我们假设它是一个字符串):

REMOVE_PATH=Server/.*/resources/SpringIOC/dataupgrader/12_55_7/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/mqm/dataupgrader/12_55_7,Server/.*/resources/indexes/12_55_7/.*\.index/.*/.*\.java

我试图使用shopt但它没有做任何事情,这是我使用的命令:

shopt -s extglob;echo ${FULL_PATH//@($"{REMOVE_PATH}")}

* FULL_PATH变量是动态的,可以改变,所以这就是我把它放在参数中的原因。

bash shell sed
1个回答
2
投票

简单的例子来理解模式替换如何与shopt extglob一起使用:

shopt -s extglob

full_path=a/b,a/c,a/d,a/e,a/f
remove_path=a/d,a/c

echo "${full_path//@(${remove_path//,/|})?(,)}"
# a/b,a/e,a/f
# a/d and a/c where removed
# ?(,) at the end to remove comma after match if any


full_path=a/*/b,a/*/c,a/*/d,a/*/e,a/*/f
remove_path=a/*/d

echo "${full_path//@(${remove_path//,/|})?(,)}"
# a/*/e,a/*/f
# here a/*/b was removed because in a/*/d * matches every character including / so a/*/d longest match is a/*/b,a/*/c,a/*/d

请注意,模式中具有特殊含义的字符可以使用反斜杠\进行转义

full_path='a/*/b,a/*/c,a/*/d,a/*/e,a/*/f'
remove_path='a/\*/d,a/\*/c'

echo "${full_path//@(${remove_path//,/|})?(,)}"
# a/*/b,a/*/e,a/*/f

否则匹配除/之外的每个字符,例如可以使用以下模式*([^/]):除/之外的0个或更多字符

full_path='a/*/b,a/*/c,a/hello/d,a/*/e,a/*/f'
remove_path='a/*([^/])/d,a/\*/c'


echo "${full_path//@(${remove_path//,/|})?(,)}"
# a/*/b,a/*/e,a/*/f
© www.soinside.com 2019 - 2024. All rights reserved.