arrays - 将部分文件名分配给bash中的变量
问题描述
我在一个文件夹中有一个文件列表,我正在尝试以非常特定的方式在 .json 文件中构建一个列表。基本上取文件名的第一、第二和第三部分,为它们分配变量,然后传递它们。
文件名:
a_test_1-aws.xml
b_test_2-aws.xml
a_stage_3-az.xml
c_prod_1-az.xml
.json 文件中的记录示例:
{"name":"$a | $b - $c", "value":"/root/environment/$d"}
它应该是什么样子:
{"name":"a | test_1 - aws", "value":"/root/environment/a_test_1-aws.xml"},
{"name":"b | test_2 - aws", "value":"/root/environment/b_test_2-aws.xml"},
{"name":"a | stage_3 - az", "value":"/root/environment/a_stage_3-az.xml"},
{"name":"c | prod_1 - az", "value":"/root/environment/c_prod_1-az.xml"}
在哪里:
$a = a/b/c (anything that goes before "_" sign)
$b = test/stage/prod (anything that goes before the "-" sign)
$c = aws/az (anything that goes before ".xml")
$d = "a_test_1-aws.xml" (the .xml file name itself)
解决方案
您可以遍历目录中的所有 xml 文件名,并在每一行中拆分变量。然后将生成的结果添加到 json_file:
#!/bin/bash
# template
JSON_STRING='{"name":"%s","value":"%s"},\n'
for file in $(ls *xml); do
A=$(echo $file | cut -d "_" -f1)
B=$(echo $file | cut -d "_" -f2-3 | cut -d '-' -f1)
C=$(echo $file | cut -d "-" -f2 | cut -d "." -f1)
D=$(echo $file)
# using readlink to get the full path
printf "$JSON_STRING" "$A | $B - $C" "$(readlink -f $D)" >> json_file
done
# removing extra comma
truncate -s-2 json_file
推荐阅读
- excel - excel根据多个单元格值从列表中创建多个文件夹
- javascript - 使用 Keycloak 保护项目的前端(React.js)部分就足够了吗?
- sql - 在 where 子句中与 n 合并
- python - Pandas Python 通过字段进行高级过滤以创建集合
- c# - 泛型中的接口约束
- pseudocode - 如何在伪代码中使用while循环
- python-3.x - 在配置中调用 hydra.utils.instantiate
- flutter - 在 null 上调用了 getter 'length'。Receiver null 尝试调用 'length' list.bilder
- python - 将 python 脚本中的值获取到 powershell 脚本中
- r - R Shiny --> 有条件地突出显示条形图