替换文件路径的中间,同时保留文件名在末尾?

替换文件路径的中间,同时保留文件名在末尾?

我正在尝试使用 bash 操作文件路径。我的目标的第一部分已经完成,我将文件路径的前半部分替换为本地计算机上的路径。

$> fp=$"/projects/bison/git/bison_20190405/assessment/LWR/validation/HBEP/analysis/BK363/HBEP_BK363_out.csv"
$> echo $fp | 
    sed -E "s#/projects/bison/git/bison_[0-9]{8}#/Users/djm/Documents/projects/bison#"

$> /Users/djm/Documents/projects/bison/assessment/LWR/validation/HBEP/analysis/BK363/HBEP_BK363_out.csv

下一部分我遇到了麻烦。我想用 替换/analysis/和 文件名之间的所有内容/doc/figures/FILENAME,包括分析。我已经能够使用 Rscript 创建此功能,但无法弄清楚如何将文件名保留在管道语句中。

预期输入:

/Users/djm/Documents/projects/bison/assessment/LWR/validation/HBEP/analysis/BK363/HBEP_BK363_out.csv

预期输出:

/Users/djm/Documents/projects/bison/assessment/LWR/validation/HBEP/doc/figures/HBEP_BK363_out.csv

这是我当前的 Rscript 以及必要的正则表达式:

library(dplyr)
library(stringr)

test <- "/projects/bison/git/bison_20190405/assessment/LWR/validation/HBEP/analysis/BK363/HBEP_BK363_out.csv"

str_replace_all(test, "/projects/bison/git/bison_[0-9]{8}",
                      "Users/djm/Documents/projects/bison") %>% 
  str_replace_all("(?:analysis).*$", 
                  paste0("doc/figures/", basename(.)))

#> [1] "Users/djm/Documents/projects/bison/assessment/LWR/validation/HBEP/doc/figures/HBEP_BK363_out.csv"

创建于 2019-04-09,作者为代表包(v0.2.1)

答案1

再次使用 sed 即可

 sed 's#/analysis/.\+/#/doc/figures/#'

对于您的输入:

$ echo /Users/djm/Documents/projects/bison/assessment/LWR/validation/HBEP/analysis/BK363/HBEP_BK363_out.csv | \
sed 's#/analysis/.\+/#/doc/figures/#'

/Users/djm/Documents/projects/bison/assessment/LWR/validation/HBEP/doc/figures/HBEP_BK363_out.csv

相关内容