【问题标题】:bash copy file where some of the filename is not knownbash 复制文件,其中某些文件名未知
【发布时间】:2013-03-07 00:16:42
【问题描述】:

在 bash 脚本中,我想复制一个文件,但文件名会随着时间而改变。 但是,文件名的开头和结尾将保持不变。

有没有办法让我得到这样的文件:

  cp start~end.jar

~可以是什么?

cp 命令将在 ubuntu 机器上运行一个 bash 脚本,如果这有所作为的话。

【问题讨论】:

    标签: bash


    【解决方案1】:

    glob (start*end) 将为您提供所有匹配的文件。

    查看 bash 手册的 Expansion > Pathname Expansion > Pattern Matching 部分以获得更具体的控制

       *      Matches any string, including the null string.
       ?      Matches any single character.
       [...]  Matches any one of the enclosed characters.  A pair of characters separated by a hyphen denotes a range expression; any character that sorts between those two characters, inclusive, using the current locale's collat-
              ing sequence and character set, is matched.  If the first character following the [ is a !  or a ^ then any character not enclosed is matched.  The sorting order of characters in range expressions  is  determined  by
              the  current locale and the value of the LC_COLLATE shell variable, if set.  A - may be matched by including it as the first or last character in the set.  A ] may be matched by including it as the first character in
              the set.
    

    如果你启用extglob:

      ?(pattern-list)
             Matches zero or one occurrence of the given patterns
      *(pattern-list)
             Matches zero or more occurrences of the given patterns
      +(pattern-list)
             Matches one or more occurrences of the given patterns
      @(pattern-list)
             Matches one of the given patterns
      !(pattern-list)
             Matches anything except one of the given patterns
    

    【讨论】:

    • 一点建议;尝试使模式尽可能具体,以避免匹配比预期更多的文件。例如,如果您知道中间部分是 YYYY-MM-DD 格式的时间戳,则更喜欢 start-????-??-??-end.jar 而不是 start*end.jar。或者更好,start-@(19|20)[0-9][0-9]-@([1-9]|10|11|12)-@([1-9]|1[1-9]|2[1-9]|3[01]-end.jar。
    【解决方案2】:

    使用glob 捕获变量文本:

    cp start*end.jar
    

    【讨论】:

      猜你喜欢
      • 2020-12-24
      • 2014-11-16
      • 1970-01-01
      • 2021-03-20
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 2011-06-08
      相关资源
      最近更新 更多