bash:如何根据模式从数组中删除元素 [英] bash: how to delete elements from an array based on a pattern

查看:30
本文介绍了bash:如何根据模式从数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 bash 数组(例如所有参数的数组)并且想要删除与某个模式匹配的所有参数,或者将所有剩余的元素复制到一个新数组中.或者,反过来,保持元素匹配模式.

Say I have a bash array (e.g. the array of all parameters) and want to delete all parameters matching a certain pattern or alternatively copy all remaining elements to a new array. Alternatively, the other way round, keep elements matching a pattern.

举例说明:

x=(preffoo bar foo prefbaz baz prefbar)

并且我想删除以 pref 开头的所有内容以获得

and I want to delete everything starting with pref in order to get

y=(bar foo baz)

(订单不相关)

如果我想要一个由空格分隔的单词列表的相同内容怎么办?

What if I want the same thing for a list of words separated by whitespace?

x="preffoo bar foo prefbaz baz prefbar"

并再次删除以pref开头的所有内容以获得

and again delete everything starting with pref in order to get

y="bar foo baz"

推荐答案

要去除扁平字符串(Hulk 已经给出了数组的答案),可以打开 extglob shell 选项并运行下面展开

To strip a flat string (Hulk has already given the answer for arrays), you can turn on the extglob shell option and run the following expansion

$ shopt -s extglob
$ unset x
$ x="preffoo bar foo prefbaz baz prefbar"
$ echo ${x//pref*([^ ])?( )}
bar foo baz

*(pattern-list)?(pattern-list) 形式需要 extglob 选项.这允许您使用正则表达式(尽管与大多数正则表达式的形式不同)而不仅仅是路径名扩展(*?[).

The extglob option is needed for the *(pattern-list) and ?(pattern-list) forms. This allows you to use regular expressions (although in a different form to most regular expressions) instead of just pathname expansion (*?[).

Hulk 为数组给出的答案仅适用于数组.如果它似乎适用于扁平字符串,那只是因为在测试数组时没有先取消设置.

The answer that Hulk has given for arrays will work only on arrays. If it appears to work on flat strings, its only because in testing the array was not unset first.

例如

$ x=(preffoo bar foo prefbaz baz prefbar)
$ echo ${x[@]//pref*/}
bar foo baz
$ x="preffoo bar foo prefbaz baz prefbar"
$ echo ${x[@]//pref*/}
bar foo baz
$ unset x
$ x="preffoo bar foo prefbaz baz prefbar"
$ echo ${x[@]//pref*/}

$

这篇关于bash:如何根据模式从数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆