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

Jun*_*unk 2 bash shell loops

我在编写 bash 脚本时有点困难。所以我在几个文件中得到了一些输出,我必须定义一个新变量。但是我需要使用 2 个文件,一个是普通文本文件,另一个是 JSON 文件:

文件.txt

abcd
fghi
jklm
Run Code Online (Sandbox Code Playgroud)

文件.json

{
   "test0": "000",
   "test1": "011",
   "test2": "022"
}
{
   "test0": "100",
   "test1": "111",
   "test2": "122"
}
{
   "test0": "200",
   "test1": "211",
   "test2": "222"
}
Run Code Online (Sandbox Code Playgroud)

我需要这样定义一个新变量:

final='{"example":"$file.txt-output","tags":"$file.json-output"}'
Run Code Online (Sandbox Code Playgroud)

我找不到让脚本同时运行每个循环的方法,首先发送 file.txt 输出。

我尝试了几种方法只是为了测试,但仍然得到相同的结果,例如:

paste -- ~/file.txt ~/file.json | while read -r input1 input2
do
    echo "$input1 =  $input2"
done
Run Code Online (Sandbox Code Playgroud)

这是我得到的:

"abcd" = {
"fghi" = "test0":
"jklm" = "test1":
} =
{ =
"test0": "100",
"test1": "111",
"test2": "122",
}
Run Code Online (Sandbox Code Playgroud)

“最终”变量应该如下所示:

final='{"example":"abcd","tags":{ "test0": "000", "test1": "011", "test2": "022" }'
final='{"example":"fghi","tags":{ "test0": "100", "test1": "111", "test2": "122" }'
....
Run Code Online (Sandbox Code Playgroud)

JSON 文件看起来像这样,没有“,”,而且它不是一个数组。任何帮助将非常感激!

Cha*_*ffy 5

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
Run Code Online (Sandbox Code Playgroud)

...作为输出发出...

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
Run Code Online (Sandbox Code Playgroud)

由于这是每个项目一行,因此标准while IFS= read -r final; do循环将正确处理它。