gpt4 book ai didi

bash - 如何在 Bash 中同时循环两个文件(一个文本文件,一个json文件)?

转载 作者:行者123 更新时间:2023-12-02 01:24:35 24 4
gpt4 key购买 nike

我在编写 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com