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

6qfn3psc  于 2023-01-17  发布在  Shell
关注(0)|答案(1)|浏览(252)

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

abcd
fghi
jklm

file.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”变量应如下所示:

final='{"example":"abcd","tags":{ "test0": "000", "test1": "011", "test2": "022" }'
final='{"example":"fghi","tags":{ "test0": "100", "test1": "111", "test2": "122" }'
....

JSON文件看起来像这样,没有“”,也不是数组。任何帮助都将不胜感激!

im9ewurl

im9ewurl1#

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循环将正确处理它。

相关问题