将文件名的部分分配给bash

问题描述 投票:0回答:2
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"}

Where:
$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)

将字符串分为变量

a, b, c, d

使用bash
参数扩展
随着子字符串去除而直接进行直接转向。参数膨胀
arrays json bash
2个回答
0
投票
the tims从左侧的修剪,尽管第一个出现

pattern

,从左侧到最后一次出现
${var##pattern}的修剪。使用pattern
%
从右侧进行相同的扩展。

输入以短脚本将其用于分离文件中的所有名称,您将拥有:
%%
示例使用/输出
在文件中您的

#!/bin/bash while read -r d || [ -n "$d" ]; do a="${d%%_*}" ## trim from right though leftmost "_" b="${d%-*}" ## trim from right through rightmost "-" b="${b#*_}" ## trim from left through leftmost "_" c="${d%.*}" ## trim from right through rightmost "." c="${c##*-}" ## trim from left trough rightmost "-" printf "\na: %s\nb: %s\nc: %s\nd: %s\n" "$a" "$b" "$c" "$d" done < "$1"

文件名

.xml
您将拥有:

names 将文件的部分分开,而不是将它们与bash放回原处之后,您可能会更好地使用一个意识到并可以验证结果的实用程序。

$ bash splitnames.sh names a: a b: test_1 c: aws d: a_test_1-aws.xml a: b b: test_2 c: aws d: b_test_2-aws.xml a: a b: stage_3 c: az d: a_stage_3-az.xml a: c b: prod_1 c: az d: c_prod_1-az.xml

是广泛使用的工具。


您可以迭代目录中的所有XML文件名,并在每行中拆分变量。然后将生成的结果添加到JSON_FILE:
.json


如果您希望输出为JSON对象,那么使用JSON AREATE工具将是最佳方法。 JSON-PARSER

XIDEL
及其
Expath文件模块可以轻松完成您想要的工作:

jq

0
投票
如果您希望输出很漂亮。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.