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.
Use perl as the encoder; it's guaranteed to be non-buggy, is everywhere, and with pipes, it's still reasonably clean:
I was also searching for a way to output a Linux folder / file tree to some JSON or XML file. Why not use this simple terminal command:
so, just the linux tree command, and config your own parameters. Here
-X
gives XML output! For me, that's OK, and i guess there's some script to convert XML to JSON ..NOTE: I think this covers the same question.
Hello you can do that with sed and awk:
EDIT: updated to solve the problem with
"
and spaces. I use/@
as replacement pattern for"
, since/
is not a valid character for filename.Most of the Linux machine already has python. all you have to do is:
This is for . directory , you can add any path.
Yes, but the corner cases and Unicode handling will drive you up the wall. Better to delegate to a scripting language that supports it natively.
Don't use bash, use a scripting language. Untested perl example: