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

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

问题描述

是否有可能使用bash脚本到 LS 的输出格式为JSON阵列?为了有效的JSON,显示目录和文件的所有名称必须用双引号,用逗号分隔,整个事情需要被放在方括号中。即转换:

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" ]

编辑:我强烈preFER的东西,所有我的Linux服务器的工作原理;因此,而不是靠蟒蛇,但有一个纯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作为EN codeR;它保证是无车,无处不在,并与管道,它仍然是合理的清洁:

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/\n$//, <>); print encode_json(\@in)."\n";'

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

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