user7915361
user7915361

Reputation: 19

How do I print line number with the output for JQ in json file

I know there is a -n option and tried many combinations but couldn't get it to work. I'd like to print the line number and the length of the each line for the json file

cat -n traffictest.json | jq '. |length'

jq -C . | cat -n traffictest.json | jq '. |length'

Upvotes: 2

Views: 3925

Answers (2)

peak
peak

Reputation: 116880

jq has a built-in filter, input_line_number, which emits the line number of the input being read. For example, given this input:

[1,2]

"abcd"

{"a":1,"b":1,"c":1,"d":1, "e":1}

the invocation:

jq -r "\(input_line_number): \(length)" 

yields:

1: 2
3: 4
5: 5

Upvotes: 4

Thor
Thor

Reputation: 47189

If you are just interested in line-number and length, I would use awk instead, e.g.:

awk '{ print NR, length, $0 }' traffictest.json

Or if you want to keep the syntax highlighting:

paste <(jq    . traffictest.json | awk '{ print NR, length }' OFS='\t') \
      <(jq -C . traffictest.json)

Upvotes: 1

Related Questions