【问题标题】:How to check for files existence from a list ignoring case using bash如何使用bash从忽略大小写的列表中检查文件是否存在
【发布时间】:2018-09-15 18:44:34
【问题描述】:

我正在编写一个脚本,该脚本正在查看输入文件并对其进行严格处理以组成文件名。比我想检查文件是否存在但忽略大小写。

for pattern in `grep -o [[:alnum:]]......-..-.. $inputfile | tr -d - | sed 's/./&./9' | tr '[A-Z]' '[a-z]'`
do
test -e $pattern || printf "Pattern $pattern is missing.\n"
test -e $pattern && cp $pattern $dirname && printf "Pattern $pattern copied to $dirname\n" done

输入文件内容示例:

TEST,
$   (AU,PIUSALO-GO-25,AD=.25)
ROWS 5200/14100
TEST 2,
$   (AU,PIUSALO-GO-60,AD=.25)
ROWS 5200/14100

所以在我的 grep 命令之后,我将拥有 piusalogo.25piusalogo.60 作为我的文件名。实际文件的文件名可能大小写混合。如何检查文件是否存在忽略大小写?

【问题讨论】:

  • 您能否提供一个minimal reproducible example - 可以由不是您的人运行的代码(并且磁盘上没有您的/some/other/$dirname),带有输入和所需的输出(以及足够独立,如果它需要一个文件存在,它首先创建该文件)?我还建议通过shellcheck.net 运行它并修复它找到的所有内容。

标签: bash for-loop while-loop filenames


【解决方案1】:

鉴于您的问题含糊不清,很难给出明确的答案。

在 bash 中,你可以做这样的事情

files=(*)               # array of the files in the current directory
file="Foo.Bar.txt"

for f in "${files[@]}"; do
    if [[ "${f,,}" = "${file,,}" ]]; then
        echo "'$file' matches '$f' case insensitively"
    fi
done

演示

touch FOO.BAR.TXT foo.bar.txt fOo.BaR.tXt
# then run above code

输出

'Foo.Bar.txt' matches 'FOO.BAR.TXT' case insensitively
'Foo.Bar.txt' matches 'fOo.BaR.tXt' case insensitively
'Foo.Bar.txt' matches 'foo.bar.txt' case insensitively

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 2013-09-05
    • 2018-01-11
    • 2021-12-03
    相关资源
    最近更新 更多