【问题标题】:How to stripe only file name from while using find command如何在使用 find 命令时仅删除文件名
【发布时间】:2021-06-07 05:16:40
【问题描述】:

我在 shell 脚本中使用 find 命令从目录中搜索文件。

FileList=`find /users/tst/CS/FSP/data/out/ -name "file*.gz"` 

我得到的结果是

echo $FileList
/users/tst/CS/FSP/data/out/filename.gz

我希望结果为“FileList=filetname.gz”。我想知道我们怎样才能得到它。

【问题讨论】:

    标签: linux shell find


    【解决方案1】:

    如果你使用 bash,你可以使用 ## 和参数扩展等:

    FileList=$(while read fil;do echo ${fil##*/};done <<< $(find /users/tst/CS/FSP/data/out/ -name "file*.gz")"
    

    或者,如果您有“basename”可用,您可以按如下方式使用它:

    FileList=$(while read fil;do echo "$(basename $fil)";done <<< $(find /users/tst/CS/FSP/data/out/ -name "file*.gz")"
    

    【讨论】:

    • 我没有 basename 所以,我正在使用这个 FileList=find find /users/tst/CS/FSP/data/out/ -name "file*.gz" -type f -name "file*.gz" | cut -d "/" -f 7
    【解决方案2】:

    其他可能性(除了已经在 Raman Sailopal 的answer 中展示的解决方案)

    如果您在 Linux 上使用 GNU find,您可以使用 find-printf 操作。

    FileList=$(find /users/tst/CS/FSP/data/out/ -name "file*.gz" -printf "%f")
    

    如果你只有一个 POSIX 兼容的find,你可以过滤输出。

    FileList=$(find /users/tst/CS/FSP/data/out/ -name "file*.gz" | sed 's#.*/##')
    

    sed 命令将删除以/ 结尾的最长部分。 (我使用# 而不是通常的/ 以避免在搜索模式中引用/。)

    【讨论】:

      【解决方案3】:

      FileList=find /users/tst/CS/FSP/data/out/ -name "file*.gz" -type f -name "file*.gz" | cut -d "/" -f 8

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-28
        • 2016-05-13
        • 1970-01-01
        • 2019-09-02
        • 2018-04-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多