简体   繁体   English

在Ruby中删除部分文件路径

[英]Remove part of file path in Ruby

I am are receiving an array as a variable 我正在接收数组作为变量

Is an example 是一个例子

["/a/b/01_Sources/02_Transferred/06_CPAS/Redbull/from_MediaHouse/Transcripts/MI201711200143.xlsx", "/a/b/01_Sources/02_Transferred/06_CPAS/Redbull/from_MediaHouse/Transcripts/MI201703030110.pdf"]

The following statement creates this list: 以下语句创建此列表:

<%= var(file_list_array).map{|file| "<li>#{File.basename(file)}</li>"}.join("\n")%>

  • MI201711200143.xlsx MI201711200143.xlsx
  • MI201703030110.pdf MI201703030110.pdf
  • The following statement creates this list 以下语句创建此列表

    <%= var(file_list_array).map{|file| "<li>#{file}</li>"}.join("\n")%>
    

  • /a/b/01_Sources/02_Transferred/06_CPAS/Redbull/from_MediaHouse/Transcripts/MI201711200143.xlsx /a/b/01_Sources/02_Transferred/06_CPAS/Redbull/from_MediaHouse/Transcripts/MI201711200143.xlsx
  • /a/b/01_Sources/02_Transferred/06_CPAS/Redbull/from_MediaHouse/Transcripts/MI201703030110.pdf /a/b/01_Sources/02_Transferred/06_CPAS/Redbull/from_MediaHouse/Transcripts/MI201703030110.pdf
  • But what I would really like: 但是我真正想要的是:

  • /Redbull/from_MediaHouse/Transcripts/MI201711200143.xlsx /Redbull/from_MediaHouse/Transcripts/MI201711200143.xlsx
  • /Redbull/from_MediaHouse/Transcripts/MI201703030110.pdf /Redbull/from_MediaHouse/Transcripts/MI201703030110.pdf
  • What do I need to change to get that ? 我需要更改以获得什么?

    Assuming you have your array of file paths in an array you could do. 假设您可以将文件路径数组放在一个数组中。

    file_paths.map{|path| path.gsub(/.*(\/Redbull\/.*)/, $1) }
    

    This will replace each item with whatever is below the "Redbull" directory 这将用“ Redbull”目录下的任何内容替换每个项目

    Alternatively if you didn't want to preprocess that list you could just put it in your display code, but that will make it less clear as to what you need to send the displaying logic. 或者,如果您不希望对该列表进行预处理,则可以将其放入显示代码中,但是这样一来,对于发送显示逻辑所需的内容将变得不太清楚。

    <%= var(file_list_array).map{|file| "<li>#{file.gsub(/.*(\/Redbull\/.*)/, $1)}</li>"}.join("\n")%>
    

    Try this 尝试这个

    file_list_array[0].split("06_CPAS")[1]
    

    assuming you want to split from "06_CPAS" . 假设您要从"06_CPAS"拆分。 You can pass it as a variable too like this 您也可以像这样将其作为变量传递

    split_str = "06_CPAS"
    index = 0
    file_list_array[index].split(split_str)[1]
    

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM