作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在编写 bash 脚本时有点困难。所以我在几个文件中得到了一些输出,我必须定义一个新变量。但是我需要使用 2 个文件,一个是普通文本文件,另一个是 JSON 文件:
文件.txt
abcd
fghi
jklm
文件.json
{
"test0": "000",
"test1": "011",
"test2": "022"
}
{
"test0": "100",
"test1": "111",
"test2": "122"
}
{
"test0": "200",
"test1": "211",
"test2": "222"
}
我需要这样定义一个新变量:
final='{"example":"$file.txt-output","tags":"$file.json-output"}'
我找不到让脚本同时运行每个循环的方法,首先发送 file.txt 输出。
我尝试了几种方法只是为了测试,但仍然得到相同的结果,例如:
paste -- ~/file.txt ~/file.json | while read -r input1 input2
do
echo "$input1 = $input2"
done
这是我得到的:
"abcd" = {
"fghi" = "test0":
"jklm" = "test1":
} =
{ =
"test0": "100",
"test1": "111",
"test2": "122",
}
“最终”变量应该如下所示:
final='{"example":"abcd","tags":{ "test0": "000", "test1": "011", "test2": "022" }'
final='{"example":"fghi","tags":{ "test0": "100", "test1": "111", "test2": "122" }'
....
JSON 文件看起来像这样,没有“,”,而且它不是一个数组。任何帮助将不胜感激!
最佳答案
jq -cs --rawfile texts file.txt '
[$texts | split("\n")[] | select(. != "")] as $nonempty_text
| [$nonempty_text, .] # array with first all text lines, then all JSON
| transpose[] # zip that array into (text, json) pairs
| select(.[0] != null and .[1] != null) # ignore if we do not have both items
| {"example": .[0], "tags": .[1]} # otherwise emit output
' <file.json
...作为输出发出...
{"example":"abcd","tags":{"test0":"000","test1":"1111","test2":"2222"}}
{"example":"fghi","tags":{"test0":"100","test1":"111","test2":"122"}}
由于这是每个项目一行,因此是标准 while IFS= read -r Final; do
循环将正确处理它。
关于bash - 如何在 Bash 中同时循环两个文件(一个文本文件,一个json文件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75111891/
我是一名优秀的程序员,十分优秀!