如何解决如何仅获取字符串数组中的 .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 脚本的新手。在这方面需要你的帮助。谢谢你。 我的想法 ->
-
(find /side/containers_automation/sc/2021-05 -type f -name "*.json" > conf_search)
-
修剪初始路径(
/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 举报,一经查实,本站将立刻删除。