Skip to content
Advertisement

read the first line of a text file with JQ

Trying to see how I can read the first line of a text file using jq

I have a text file with a bunch of ids (newfile.txt )

5584157003
5584158003
5584159003
5584160003

id like to be able to just read the first line with jq.

I tried doing this

cat newfile.txt | jq '.[0]'

But getting an error of

jq: error (at <stdin>:482): Cannot index number with number

I’d like to be able to read line by line so that I can eventually run a look with that ID and be able to do stuff with it. Any ideas?

Advertisement

Answer

Use the -R argument (aka --raw-input) to tell jq that it’s receiving input as strings rather than JSON, and use input to read only a single item at a time. Thus:

jq -Rn input <yourfile

…will output:

"5584157003"

If you want to convert it to a number, that’s what tonumber is for:

jq -Rn 'input | tonumber' <yourfile

…which will output:

5584157003
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement