bash4 - 在创建正则表达式过滤器的目录内容阵列 [英] bash4 - creating array of directory contents on regex filter

查看:186
本文介绍了bash4 - 在创建正则表达式过滤器的目录内容阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一种方式,过滤目录创建一个基于正则表达式的bash的数组。

Looking for a way to create an bash array based on a regex in filtering a directory.

例如我做的:

A. local -a arr=( "$1"/* ); arr=( "${arr[@]##*/} );
- Creates array of all contents of the path sent in $1.

B. local -a arr=( "$1"/*"$2" ); arr=( "${arr[@]##*/}" );
- Creates array on filter expression in $2.

(我不知道为什么*不显示了$ 1/ *$ 2在B.如果我把2 ** S都显示了!)

(I do not know why the * is not showing up in "$1"/*"$2" in B. If I put 2 **s both show up!)

但它仅适用于一个简单的前pression:例如'的.pub' - 列出了所有的公共密钥

But it only works for a simple expression: example '.pub' - lists all public keys.

不过,如果我送'Z *。zip'to找到开头的压缩文件Z。不工作。

However if I send 'z.*.zip'to find all zip files beginning with 'z.' does not work.

我甚至尝试取出 *$ 2 ARR =($ 1/ *$ 2)
*$ 2显示不出来!

I even tried taking out the *"$2" in arr=( "$1"/*"$2" ). *"$2" not showing up!

您的帮助将是非常美联社preciated。

Your help would be much appreciated.

感谢您。

推荐答案

水珠不会在双引号扩大。你必须解除引用它:

Globs don't expand in double quotes. You have to unquote it:

local -a arr=( "$1"/*$2 ); 

要避免空白问题,你可以使用 IFS =先来抑制分词,同时还做不带引号上的水珠变量扩展。

To avoid issues with whitespace, you can use IFS="" first to inhibit word splitting while still doing glob expansion on unquoted variables.

下面是一个例子调用:

$ cat script

foo() {
  local -a arr=( "$1"/*$2 );
  echo "Matching files: " "${arr[@]}"
}

foo "." "z.*.zip"

$ ls
lobsters.png  pelican.zip  script  z.bar.zip  z.cow.txt

$ bash script
Matching files:  ./z.bar.zip

$

这篇关于bash4 - 在创建正则表达式过滤器的目录内容阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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