微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何仅获取字符串数组中的 .json 文件名以遍历文件名

如何解决如何仅获取字符串数组中的 .json 文件名以遍历文件名

如何只获取字符串数组中的 .json 文件名来遍历文件

问题: 我在路径 /side/containers_automation/sc/2021-05/ 中有 12 个 .json 文件 这个路径也可以有不同的文件扩展名。

find /side/containers_automation/sc/2021-05 -type f -name "*.json"

/side/containers_automation/sc/2021-05/ci-userstory-tlm.json
/side/containers_automation/sc/2021-05/ci-userstory-spe.json
/side/containers_automation/sc/2021-05/ci-e2e-tlm.json
/side/containers_automation/sc/2021-05/ci-userstory-dm-inbound.json
/side/containers_automation/sc/2021-05/cucumber-ci-e2e-ta-dm.json
/side/containers_automation/sc/2021-05/cucumber-ci-e2e-tlm.json
/side/containers_automation/sc/2021-05/bvt-dm.json
/side/containers_automation/sc/2021-05/ci-userstory-dm-outbound-execution.json
/side/containers_automation/sc/2021-05/ci-e2e-dm.json
/side/containers_automation/sc/2021-05/cucumber-ci-userstory-tlm.json
/side/containers_automation/sc/2021-05/ci-userstory-dm-outbound.json
/side/containers_automation/sc/2021-05/uat-dm.json

只想复制 .json 类型的文件名并在它们之前附加一个关键字(例如:automation)。 前任: 自动化-ci-userstory-tlm 自动化-cucumber-ci-e2e-ta-dm 自动化-uat-dm 等等。 并将这些名称存储在一个字符串数组中,以便我可以对其进行迭代。

我是 shell 脚本的新手。在这方面需要你的帮助。谢谢你。 我的想法 ->

  1. 通过命令获取文件

    (find /side/containers_automation/sc/2021-05 -type f -name "*.json" > conf_search)

  2. 修剪初始路径(

    /side/containers_automation/sc/2021-05) 和文件格式 (.json)

/side/containers_automation/sc/2021-05/uat-dm.json 3. 只需获取 uat,ci-userstory-tlm,ci-userstory-tlm ,将其放入字符串数组中 4. 迭代这个 我知道这是一个复杂而冗长的解决方案。

解决方法

您只想要数组中特定目录中的所有 JSON 文件,减去路径并将 automation- 添加到名称的开头?

使用 bash 参数替换很容易操作以完整文件名开头的数组元素:

# Populate the array with the full paths to the files
filenames=( /side/containers_automation/sc/2021-05/*.json )
# Remove the path from each element
filenames=( "${filenames[@]##*/}" )
# Remove the .json extension from each element
filenames=( "${filenames[@]/%.json}" )
# Prepend automation- to each element
filenames=( "${filenames[@]/#/automation-}" )
# And show the final results for the sake of the example
declare -p filenames

或者,使用显式循环一次向数组添加一个文件,并使用 basename(1) 一次性去除路径和扩展名,而不是两步:

declare -a filenames
for file in /side/containers_automation/sc/2021-05/*.json; do
    filenames+=( "automation-$(basename "$file" .json)" )
done
declare -p filenames

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?