首页 > 解决方案 > 将部分文件名分配给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)

标签: arraysjsonbash

解决方案


您可以遍历目录中的所有 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

推荐阅读