在 bash 中进行管道传输时获取行号(换行符计数)

Get line number (count of newlines) when piping in bash

我正在使用 jq 将 json 个文档的文件转换为 json 个不同形状的文档的文件。我需要输出文档有一个连续的正 id。我可以访问等于看到的换行数的变量吗?

gzcat input.gz | jq -r '"{\"id\":???, \"foo\":\(.foo)}"' > output
# can anything take the place of ??? to give 0..n?

如果您的 jq 有 input_line_number,您也许可以使用它。这是一个打字稿,说明了它的作用:

$ jq 'input_line_number'
"a"
1
"b"
2

(在上面,输入行紧跟在输出行之后。)

同样,下面是 foreachinputs 可以一起使用的方式:

$ jq -n 'foreach inputs as $line (0; .+1; "line \(.) is \($line)")'
"abc"
"line 1 is abc"
123
"line 2 is 123"

如果您的 jq 没有 foreach,那么您可能会发现 reduce 足以满足您的需求:

$ jq -s -r 'reduce .[] as $line
    ( [0,""]; .[0]+=1 | .[1] += "line \(.[0]) is \($line)\n")
    | .[1]'

输入:

"abc"
123

输出:

line 1 is abc
line 2 is 123