如何读取 csv 中一列的每个单元格并将每个单元格作为 bash 中 jq 的输入
How to read each cell of a column in csv and take each as input for jq in bash
我正在尝试读取 CSV 的每个单元格并将其视为 JQ 命令的输入。下面是我的代码:
line.csv
| Line |
|:---- |
| 11 |
| 22 |
| 33 |
读取 CSV 的代码:
while read line
do
echo "Line is : $line"
done < line.csv
输出:
Line is 11
Line is 22
jq命令
jq 'select(.scan.line == '""') | .scan.line,"|", .scan.service,"|", .scan.comment_1,"|", .scan.comment_2,"|", .scan.comment_3' linescan.json | xargs
我有一个 linescan.json,它具有线路、服务、comment_1、comment_2、comment_3
的值
我想读取 csv 的每个值并处理 jq 查询中提到 $1 的输入。
请指教
给定输入文件和所需的输出:
- line.csv
22,Test1
3389,Test2
10,Test3
- linescan.json
{
"scan": {
"line": 3389,
"service": "Linetest",
"comment_1": "Line is tested1",
"comment_2": "Line is tested2",
"comment_3": "Line is tested3"
}
}
- 期望的输出:
Test2 | 3389 | Linetest | Line is tested1 | Line is tested2 | Line is tested3
这是 jq
的解决方案:
这是在黑暗中拍摄的,因为您没有指定输出应该是什么样子:
jq -sr --rawfile lineArr line.csv '
(
$lineArr | split("\n") | del(.[-1]) | .[] | split(",")
) as [$lineNum,$prefix] |
.[] | select(.scan.line == ($lineNum | tonumber)) |
[
$prefix,
.scan.line,
.scan.service,
.scan.comment_1,
.scan.comment_2,
.scan.comment_3
] |
join(" | ")
' linescan.json
更新:使用 jq 1.5:
#!/bin/bash
jq -sr --slurpfile lineArr <(jq -R 'split(",")' line.csv) '
($lineArr | .[]) as [$lineNum,$prefix] |
.[] | select(.scan.line == ($lineNum | tonumber)) |
[
$prefix,
(.scan.line | tostring),
.scan.service,
.scan.comment_1,
.scan.comment_2,
.scan.comment_3
] |
join(" | ")
' linescan.json
我正在尝试读取 CSV 的每个单元格并将其视为 JQ 命令的输入。下面是我的代码:
line.csv
| Line |
|:---- |
| 11 |
| 22 |
| 33 |
读取 CSV 的代码:
while read line
do
echo "Line is : $line"
done < line.csv
输出:
Line is 11
Line is 22
jq命令
jq 'select(.scan.line == '""') | .scan.line,"|", .scan.service,"|", .scan.comment_1,"|", .scan.comment_2,"|", .scan.comment_3' linescan.json | xargs
我有一个 linescan.json,它具有线路、服务、comment_1、comment_2、comment_3
的值我想读取 csv 的每个值并处理 jq 查询中提到 $1 的输入。
请指教
给定输入文件和所需的输出:
- line.csv
22,Test1
3389,Test2
10,Test3
- linescan.json
{
"scan": {
"line": 3389,
"service": "Linetest",
"comment_1": "Line is tested1",
"comment_2": "Line is tested2",
"comment_3": "Line is tested3"
}
}
- 期望的输出:
Test2 | 3389 | Linetest | Line is tested1 | Line is tested2 | Line is tested3
这是 jq
的解决方案:
这是在黑暗中拍摄的,因为您没有指定输出应该是什么样子:
jq -sr --rawfile lineArr line.csv '
(
$lineArr | split("\n") | del(.[-1]) | .[] | split(",")
) as [$lineNum,$prefix] |
.[] | select(.scan.line == ($lineNum | tonumber)) |
[
$prefix,
.scan.line,
.scan.service,
.scan.comment_1,
.scan.comment_2,
.scan.comment_3
] |
join(" | ")
' linescan.json
更新:使用 jq 1.5:
#!/bin/bash
jq -sr --slurpfile lineArr <(jq -R 'split(",")' line.csv) '
($lineArr | .[]) as [$lineNum,$prefix] |
.[] | select(.scan.line == ($lineNum | tonumber)) |
[
$prefix,
(.scan.line | tostring),
.scan.service,
.scan.comment_1,
.scan.comment_2,
.scan.comment_3
] |
join(" | ")
' linescan.json