【问题标题】:Print working directory into output filename将工作目录打印到输出文件名中
【发布时间】:2021-11-25 02:12:12
【问题描述】:

我目前正在运行一个执行并输出结果的 bash 脚本。输出日志当前与 {basename}.out 一起存储。例如,

home/usr/dev 存储为dev.out

但是,我想将该文件命名为完整的工作打印目录,例如 home_usr_dev.out

如何将文件重命名为完整路径或工作目录?

【问题讨论】:

  • soo cd home/usr/dev 然后mv dev.out home_usr_dev.out ?
  • 为什么包含home/usr/dev没有前导/

标签: string bash output


【解决方案1】:

如 cmets 中所述,手动执行此操作仅相当于使用 cdmv shell 内置函数。

但是如果你想在 Bash 中自动“计算”输出文件名,假设$path(小写!)表示输入文件或目录的完整路径,你可以这样做:

#!/usr/bin/env bash
out_file() {
  local tmp="$1"
  tmp="${tmp#/}"      # remove leading `/`
  tmp="${tmp//\//_}"  # replace all `/`s with `_`s
  printf "%s" "$tmp"
}
path="/home/usr/dev"
# or path="$PWD"  # if you want to use the current working directory

out="$(out_file "$path").out"  # on this example, gives "home_usr_dev.out"

echo "Logs…" >> "$out"         # append "Logs…" to file ./home_usr_dev.out

为了完整起见,请注意${tmp//\//_} 短语对应于a Pattern Substitution(在 Bash 中可用,但在 POSIX shell 中不可用),可以这样解析(假设忽略空格):

${tmp // \/ / _}
   ↓  ↓  ↓  ↓ ↓
   ↓  ↓  ↓  ↓ the character _.
   ↓  ↓  ↓  with
   ↓  ↓  of / (escape needed here)
   ↓  then replace all occurrences  
   Get the value of $tmp,

【讨论】:

    猜你喜欢
    • 2012-09-30
    • 1970-01-01
    • 2015-08-31
    • 2011-12-19
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多