【问题标题】:How to use a bash variable to hold the format of find's printf statement [duplicate]如何使用 bash 变量来保存 find 的 printf 语句的格式 [重复]
【发布时间】:2018-09-27 18:47:09
【问题描述】:

bash 如何使用变量作为find-printf 语句的格式?我正在尝试转换以下内容:

find ./ -type f -printf "File: %p has modification time [%TY-%Tm-%Td %TH:%TM:%TS %TZ]\n"

打印以下内容:

File: ./file_20180926_220000.txt has modification time [2018-09-26 22:00:00.0000000000 CDT]
File: ./file_20180926_210000.txt has modification time [2018-09-26 21:00:00.0000000000 CDT]
File: ./file_20180926_230000.txt has modification time [2018-09-26 23:00:00.0000000000 CDT]

我希望将 printf 语句保存在变量中,如下图所示(但失败)。

operation="-printf \"File: %p has modification time [%TY-%Tm-%Td %TH:%TM:%TS %TZ]\n\""
find ./ -type f $operation

输出是:

find: paths must precede expression: %p
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec|time] [path...] [expression]

更简单的 printf 格式可以工作,就像我只使用 operation="-printf %p" 一样,但只要我在格式中使用空格,就会出现上述错误。我还尝试使用\ 转义空格,但我无法让它工作。

如果可能,我想避免使用eval,除非有人可以建议如何在这种情况下安全地使用它。

注意: 以下工作,但需要两个变量,而我宁愿只保留一个:

operation="-printf"
format="File: %p has modification time [%TY-%Tm-%Td %TH:%TM:%TS %TZ]\n"
find ./ -type f $operation "$format"
File: ./file_20180926_220000.txt has modification time [2018-09-26 22:00:00.0000000000 CDT]
File: ./file_20180926_210000.txt has modification time [2018-09-26 21:00:00.0000000000 CDT]
File: ./file_20180926_230000.txt has modification time [2018-09-26 23:00:00.0000000000 CDT]

【问题讨论】:

    标签: bash variables format find printf


    【解决方案1】:

    您可以将单个参数存储在常规变量中:

    print_format="File: %p has modification time [%TY-%Tm-%Td %TH:%TM:%TS %TZ]\n"
    find ./ -type f -printf "$print_format"
    

    或者您可以将一个或多个参数存储在一个数组中:

    find_options=( -printf "File: %p has modification time [%TY-%Tm-%Td %TH:%TM:%TS %TZ]\n" )
    find ./ -type f "${find_options[@]}"
    

    【讨论】:

      猜你喜欢
      • 2015-04-16
      • 2020-01-18
      • 1970-01-01
      • 2012-03-22
      • 2015-11-13
      • 2019-08-20
      • 2016-04-23
      • 1970-01-01
      • 2016-06-15
      相关资源
      最近更新 更多