【问题标题】:Shell Script - Get name of dynamically generated fileShell 脚本 - 获取动态生成的文件的名称
【发布时间】:2015-11-08 14:32:14
【问题描述】:

我对 shell 脚本很陌生,因此我现在不太关心它。 我有一个应用程序,它创建了一个名称未知的 java 文件,现在我尝试编写一个需要这个名称的脚本。
文件的已知名称是/target/plugin-<dyn>.jar<dyn> 部分未知,几乎可以是任何东西(顺便说一句,它主要是带有可变文本部分的版本号)。
现在我想将plugin-<dyn>(没有.jar)保存在一个变量中以备后用。我在网上找了很多,但我找不到解决方案。

【问题讨论】:

    标签: regex file shell


    【解决方案1】:

    如果您需要获取不带扩展名的文件名.jar。你可以参考下面我的 bash 脚本:

    # for loop all files in target directory that matched plugin-*.jar
    for f in target/plugin-*.jar
    do 
        # print file name without extension .jar
        echo ${f%.*}
    done
    

    更新:

    # for loop all files in target directory that matched plugin-*.jar
    for f in target/plugin-*.jar
    do 
        # print file name without extension .jar
        filename="${f##*/}" # get plugin-*.jar
        echo ${filename%.*} # print plugin-* without jar
    done
    

    【讨论】:

    • 需要添加 shopt -s nullglob 以获取不匹配的情况。
    • 这也返回路径,./target/ 但我只需要文件名
    • 我找到了解决办法,先用 cd 进入目录,然后用 cd 回到父目录
    【解决方案2】:

    试试这个

    filename="/target/plugin-<dyn>.jar"
    echo ${filename} | awk -F [/.] '{print $(NF - 1)}'
    echo ${filename} | sed 's/.*\/\([^/]*\)\.jar/\1/'
    

    但如果&lt;dyn&gt; 有斜线、逗号或点。它可能不起作用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      • 2013-04-14
      • 2018-08-09
      相关资源
      最近更新 更多