gpt4 book ai didi

bash - 带空格的 shell glob 扩展

转载 作者:行者123 更新时间:2023-11-29 09:48:39 24 4
gpt4 key购买 nike

我想编写一个 Posix shell 脚本函数来匹配包含需要扩展的空格和 glob 字符 (*?) 的模式。在 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*'

最佳答案

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

ls -l "hello world"*
ls -l "hello world"*".txt"

然后您可以将带引号的字符串传递给 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"*'

关于bash - 带空格的 shell glob 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15670396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com