shell Linux bash -查找模式包含空格的文件[重复]

rryofs0p  于 2023-01-31  发布在  Shell
关注(0)|答案(1)|浏览(149)
    • 此问题在此处已有答案**:

When to wrap quotes around a shell variable?(5个答案)
十小时前关门了。
我在Linux上使用了一个shell脚本,它根据一个模式来处理某个目录中的一些文件。这个模式可以包含空格。问题是我如何获得与这个模式匹配的文件列表?

Example:
This is the list of files:
file_without_spaces.vol-1.txt
file_without_spaces.vol-2.txt
file with spaces.vol-1.txt
file with spaces.vol-2.txt
file with spaces.vol-3.txt

Result when the pattern is "file_without_spaces":
file_without_spaces.vol-1.txt
file_without_spaces.vol-2.txt

Result when the pattern is "file with spaces":
file with spaces.vol-1.txt
file with spaces.vol-2.txt
file with spaces.vol-3.txt

模式来自一个env变量,我们称之为PATTERN。
模式的grep操作不起作用,因为它可能包含grep无法处理的空格。使用模式作为参数进行查找也是如此,例如find <dir> -name $PATTERN

gt0wga4j

gt0wga4j1#

Grep和find可以很好地处理空格,你只需要引用它们:

find <dir> -name "$PATTERN"

相关问题