Is it possible to use a bash script to format the output of the ls
to a json array? To be valid json, all names of the dirs and files need to be wrapped in double quotes, seperated by a comma, and the entire thing needs to be wrapped in square brackets. I.e. convert:
jeroen@jeroen-ubuntu:~/Desktop$ ls
foo.txt bar baz
to
[ "foo.txt", "bar", "baz" ]
edit: I strongly prefer something that works across all my Linux servers; hence rather not depend on python, but have a pure bash solution.
Personnaly, I would code script that would run the command ls, send the output to a file of you choice while parsing the output to make format it to a valid JSON format.
I'm sure that a simple Bash file will do the work.
Bash ouput
Should be pretty easy.
then run:
but python would be even easier
If you know that no filename contains newlines, use jq:
ls | jq -R -s -c 'split("\n")[:-1]'
Short explanation of the flags to jq:
-R
treats the input as string instead of JSON-s
joins all lines into an array-c
creates a compact output[:-1]
removes the last empty string in the output arrayThis requires version 1.4 or later of jq. Try this if it doesn't work for you:
ls | jq -R '[.]' | jq -s -c 'add'
Here's a bash line
Won't properly deal with
"
,\
or some commas in the name of the file. Also, ifls
puts newlines between filenames, so will this.Can't you use a python script like this?
I didn't check if it works, but you can find the specification here