I am trying to manipulate a file path using bash. The first part of my goal has been completed, where I replace the first half of the file path with the path on my local computer.

$> 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

The next part I am having trouble with. I would like to replace everything between /analysis/ and the file name with /doc/figures/FILENAME, including analysis. I have been able to create this functionality using an Rscript but can't figure out how I would keep the filename in the pipe statement.

Expected Input:


Expected Output:


Here is my current Rscript with the necessary regexp:


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") %>% 
                  paste0("doc/figures/", basename(.)))

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

Created on 2019-04-09 by the reprex package (v0.2.1)


Just use sed again

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

For your input:

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

  • hmmm it's not working for me. I'm on macOS if that makes a difference. I've seen that sed can act differently depending. – dylanjm Apr 9 at 15:44
  • @dylanjm does it work if you replace \+ with * ? – JShorthouse Apr 9 at 15:45
  • that worked perfectly! Thank you! – dylanjm Apr 9 at 15:46
  • 1
    @dylanjm Alright, it seems that \+ is GNU specific. * should work fine, but keep in mind that \+ means "one or more characters" while * means "zero or more", so this would trip up on something like /analysis//BK363/HBEP_BK363_out.csv(notice the doubleslash which will still be a valid filename in bash, but will cause sed to not replace the BK363 after.) – JShorthouse Apr 9 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.