gpt4 book ai didi

bash - 文件通配无需分词?

转载 作者:行者123 更新时间:2023-12-02 21:15:21 25 4
gpt4 key购买 nike

这是一个简化的示例,希望能说明我的问题。

我有一个脚本,它采用一个参数作为通配符。有时此通配符包含空格。我需要能够使用通配符进行通配符,但分词导致它失败。

例如,考虑以下示例文件:

$ ls -l "/home/me/dir with whitespace"
total 0
-rw-r--r-- 1 me Domain Users 0 Jun 25 16:58 file_a.txt
-rw-r--r-- 1 me Domain Users 0 Jun 25 16:58 file_b.txt

我的脚本 - 简化为使用硬编码模式变量 - 如下所示:

#!/bin/bash

# Here this is hard coded, but normally it would be passed via parameter
# For example: pattern="${1}"
# The whitespace and wildcard can appear anywhere in the pattern
pattern="/home/me/dir with whitespace/file_*.txt"

# First attempt: without quoting
ls -l ${pattern}

# Result: word splitting AND globbing
# ls: cannot access /home/me/dir: No such file or directory
# ls: cannot access with: No such file or directory
# ls: cannot access whitespace/file_*.txt: No such file or directory


####################

# Second attempt: with quoting
ls -l "${pattern}"

# Result: no word splitting, no globbing
# ls: cannot access /home/me/dir with whitespace/file_*.txt: No such file or directory

有没有办法启用通配符,但禁用分词?
除了手动转义模式中的空格之外,我还有其他选择吗?

最佳答案

不要将 glob 保留在引号内以便能够扩展它:

pattern="/home/me/dir with whitespace/file_"

ls -l "${pattern}"*

编辑:

根据编辑的问题和评论,您可以使用查找:

find . -path "./$pattern" -print0 | xargs -0 ls -l

关于bash - 文件通配无需分词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31061753/

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