将 bash `ls` 输出转换为 json 数组 [英] convert bash `ls` output to json array

查看:60
本文介绍了将 bash `ls` 输出转换为 json 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 bash 脚本将 ls 的输出格式化为 json 数组?要成为有效的json,目录和文件的所有名称都需要用双引号括起来,用逗号分隔,并且整个东西需要用方括号括起来.IE.转换:

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

[ "foo.txt", "bar", "baz" ]

我非常喜欢可以在我所有的 Linux 服务器上运行的东西;因此,而不是依赖于 python,而是有一个纯粹的 bash 解决方案.

edit: I strongly prefer something that works across all my Linux servers; hence rather not depend on python, but have a pure bash solution.

推荐答案

使用 perl 作为编码器;它保证没有问题,无处不在,而且有管道,它仍然相当干净:

Use perl as the encoder; it's guaranteed to be non-buggy, is everywhere, and with pipes, it's still reasonably clean:

ls | perl -e 'use JSON; @in=grep(s/
$//, <>); print encode_json(@in)."
";'

这篇关于将 bash `ls` 输出转换为 json 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆