带空格的 shell glob 扩展

Hal*_*ary 2 bash shell glob sh

我想编写一个 Posix shell 脚本函数,该函数将匹配需要扩展的空格和通配符 (*?) 的模式。在 Python 中,glob.glob('/tmp/hello world*')将返回正确的列表。我如何在 shell 中执行此操作?

#!/bin/sh

## this function will list
## all of the files in the /tmp
## directory that match pattern
f() {
  PATTERN="$1"
  ls -1 "/tmp/$PATTERN"
}

touch '/tmp/hello world {1,2,3}.txt'
f 'hello world*'
Run Code Online (Sandbox Code Playgroud)

cra*_*535 5

您可以将除*引号之外的所有内容括起来:

ls -l "hello world"*
ls -l "hello world"*".txt"
Run Code Online (Sandbox Code Playgroud)

然后,您可以将带引号的字符串传递给f(). 使用里面的字符串f()将需要eval.

#!/bin/sh

## this function will list
## all of the files in the /tmp
## directory that match pattern
f() {
  PATTERN=$1
  eval ls -1 "/tmp/$PATTERN"
}

touch '/tmp/hello world {1,2,3}.txt'
f '"hello world"*'
Run Code Online (Sandbox Code Playgroud)

  • 警告:如果模式包含错误的 shell 元字符(如 `'`、`<`、`>` 等...),`eval` 可能会导致非常糟糕的行为 (2认同)