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:
是否可以使用bash脚本将ls的输出格式化为json数组?要成为有效的json,所有dirs和文件的名称都需要用双引号括起来,用逗号分隔,整个文件需要用方括号括起来。即转换:
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.
编辑:我非常喜欢能在我所有的Linux服务器上工作的东西;因此,与其依赖python,不如使用纯粹的bash解决方案。
11 个解决方案
#1
12
Use perl as the encoder; it's guaranteed to be non-buggy, is everywhere, and with pipes, it's still reasonably clean:
使用perl作为编码器;它保证不会有bug,到处都是,而且有了管道,它还是相当干净的:
ls | perl -e 'use JSON; @in=grep(s/\n$//, <>); print encode_json(\@in)."\n";'
#2
16
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.
是的,但是转角案例和Unicode处理将会使您陷入困境。最好委托给本地支持它的脚本语言。
$ ls
あ a "a" à a b 私
$ python -c 'import os, json; print json.dumps(os.listdir("."))'
["\u00e0", "\"a\"", "\u79c1", "a b", "\u3042", "a"]
#3
10
Hello you can do that with sed and awk:
你好,你可以用sed和awk完成:
ls | awk ' BEGIN { ORS = ""; print "["; } { print "\/\@"$0"\/\@"; } END { print "]"; }' | sed "s^\"^\\\\\"^g;s^\/\@\/\@^\", \"^g;s^\/\@^\"^g"
EDIT: updated to solve the problem with "
and spaces. I use /@
as replacement pattern for "
, since /
is not a valid character for filename.
编辑:更新以解决“和空格”的问题。我用/@作为替换模式,因为/不是文件名的有效字符。
#4
9
If you know that no filename contains newlines, use jq:
如果您知道没有文件名包含换行,请使用jq:
ls | jq -R -s -c 'split("\n")'
ls| jq -R -s -c 'split("\n")
Short explanation of the flags to jq:
向jq简要说明旗帜:
-
-R
treats the input as string instead of JSON - -R将输入视为字符串,而不是JSON
-
-s
joins all lines into an array - -s将所有行连接到一个数组中
-
-c
creates a compact output - -c生成一个紧凑的输出
This requires version 1.4 or later of jq. Try this if it doesn't work for you:
这需要版本1.4或更高版本的jq。如果不适合你,试试这个:
ls | jq -R '[.]' | jq -s -c 'add'
| jq -R '[。' | jq -s -c 'add'
#5
1
Here's a bash line
这里有一个bash
echo '[' ; ls --format=commas|sed -e 's/^/\"/'|sed -e 's/,$/\",/'|sed -e 's/\([^,]\)$/\1\"\]/'|sed -e 's/, /\", \"/g'
Won't properly deal with "
, \
or some commas in the name of the file. Also, if ls
puts newlines between filenames, so will this.
不会正确处理“,\或文件名中的一些逗号。同样,如果ls在文件名之间设置了换行符,那么这个也会。
#6
1
Most of the Linux machine already has python. all you have to do is:
大多数Linux机器已经有了python。你所要做的就是:
python -c 'import os, json; print json.dumps(os.listdir("/yourdirectory"))'
This is for . directory , you can add any path.
这是。目录,您可以添加任何路径。
#7
0
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.
就个人而言,我将编写运行命令ls的脚本,将输出发送到您选择的文件,同时解析输出,使其格式化为有效的JSON格式。
I'm sure that a simple Bash file will do the work.
我确信一个简单的Bash文件可以完成这项工作。
Bash输出
#8
0
Can't you use a python script like this?
难道你不能使用这样的python脚本吗?
myOutput = subprocess.check_output["ls"]
output = ["+str(e)+" for e in myOutput]
return output
I didn't check if it works, but you can find the specification here
我没有检查它是否有效,但是你可以在这里找到规范。
#9
0
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:
我还在寻找将linux文件夹/文件树输出到某个JSON或XML文件的方法。为什么不使用这个简单的终端命令:
$ tree --dirsfirst --noreport -n -X -i -s -D -f -o my.xml
$ tree——dirsfirst——noreport -n -X -i -s -D -f -o my.xml
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 https://unix.stackexchange.com/questions/90115/convert-output-of-tree-command-to-json-format/ covers the same question.
因此,只需使用linux tree命令,并配置自己的参数。这里-X给出XML输出!对我来说,这没问题,我想应该有一些脚本可以将XML转换成JSON。注意:我认为https://unix.stackexchange.com/questions/90115/convert-out -of-tree- to-json-format/涵盖了同样的问题。
#10
-1
Don't use bash, use a scripting language. Untested perl example:
不要使用bash,使用脚本语言。未经考验的perl示例:
use JSON;
my @ls_output = `ls`; ## probably better to use a perl module to do this, like DirHandle
print encode_json( @ls_output );
#11
-1
Should be pretty easy.
应该很容易。
$ cat ls2json.bash
#!/bin/bash
echo -n '['
for FILE in $(ls | sed -e 's/"/\\"/g')
do
echo -n \"${FILE}\",
done
echo -en \\b']'
then run:
然后运行:
$ ./ls2json.bash > json.out
but python would be even easier
但是python会更简单
import os
directory = '/some/dir'
ls = os.listdir(directory)
dirstring = str(ls)
print dirstring.replace("'",'"')
#1
12
Use perl as the encoder; it's guaranteed to be non-buggy, is everywhere, and with pipes, it's still reasonably clean:
使用perl作为编码器;它保证不会有bug,到处都是,而且有了管道,它还是相当干净的:
ls | perl -e 'use JSON; @in=grep(s/\n$//, <>); print encode_json(\@in)."\n";'
#2
16
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.
是的,但是转角案例和Unicode处理将会使您陷入困境。最好委托给本地支持它的脚本语言。
$ ls
あ a "a" à a b 私
$ python -c 'import os, json; print json.dumps(os.listdir("."))'
["\u00e0", "\"a\"", "\u79c1", "a b", "\u3042", "a"]
#3
10
Hello you can do that with sed and awk:
你好,你可以用sed和awk完成:
ls | awk ' BEGIN { ORS = ""; print "["; } { print "\/\@"$0"\/\@"; } END { print "]"; }' | sed "s^\"^\\\\\"^g;s^\/\@\/\@^\", \"^g;s^\/\@^\"^g"
EDIT: updated to solve the problem with "
and spaces. I use /@
as replacement pattern for "
, since /
is not a valid character for filename.
编辑:更新以解决“和空格”的问题。我用/@作为替换模式,因为/不是文件名的有效字符。
#4
9
If you know that no filename contains newlines, use jq:
如果您知道没有文件名包含换行,请使用jq:
ls | jq -R -s -c 'split("\n")'
ls| jq -R -s -c 'split("\n")
Short explanation of the flags to jq:
向jq简要说明旗帜:
-
-R
treats the input as string instead of JSON - -R将输入视为字符串,而不是JSON
-
-s
joins all lines into an array - -s将所有行连接到一个数组中
-
-c
creates a compact output - -c生成一个紧凑的输出
This requires version 1.4 or later of jq. Try this if it doesn't work for you:
这需要版本1.4或更高版本的jq。如果不适合你,试试这个:
ls | jq -R '[.]' | jq -s -c 'add'
| jq -R '[。' | jq -s -c 'add'
#5
1
Here's a bash line
这里有一个bash
echo '[' ; ls --format=commas|sed -e 's/^/\"/'|sed -e 's/,$/\",/'|sed -e 's/\([^,]\)$/\1\"\]/'|sed -e 's/, /\", \"/g'
Won't properly deal with "
, \
or some commas in the name of the file. Also, if ls
puts newlines between filenames, so will this.
不会正确处理“,\或文件名中的一些逗号。同样,如果ls在文件名之间设置了换行符,那么这个也会。
#6
1
Most of the Linux machine already has python. all you have to do is:
大多数Linux机器已经有了python。你所要做的就是:
python -c 'import os, json; print json.dumps(os.listdir("/yourdirectory"))'
This is for . directory , you can add any path.
这是。目录,您可以添加任何路径。
#7
0
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.
就个人而言,我将编写运行命令ls的脚本,将输出发送到您选择的文件,同时解析输出,使其格式化为有效的JSON格式。
I'm sure that a simple Bash file will do the work.
我确信一个简单的Bash文件可以完成这项工作。
Bash输出
#8
0
Can't you use a python script like this?
难道你不能使用这样的python脚本吗?
myOutput = subprocess.check_output["ls"]
output = ["+str(e)+" for e in myOutput]
return output
I didn't check if it works, but you can find the specification here
我没有检查它是否有效,但是你可以在这里找到规范。
#9
0
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:
我还在寻找将linux文件夹/文件树输出到某个JSON或XML文件的方法。为什么不使用这个简单的终端命令:
$ tree --dirsfirst --noreport -n -X -i -s -D -f -o my.xml
$ tree——dirsfirst——noreport -n -X -i -s -D -f -o my.xml
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 https://unix.stackexchange.com/questions/90115/convert-output-of-tree-command-to-json-format/ covers the same question.
因此,只需使用linux tree命令,并配置自己的参数。这里-X给出XML输出!对我来说,这没问题,我想应该有一些脚本可以将XML转换成JSON。注意:我认为https://unix.stackexchange.com/questions/90115/convert-out -of-tree- to-json-format/涵盖了同样的问题。
#10
-1
Don't use bash, use a scripting language. Untested perl example:
不要使用bash,使用脚本语言。未经考验的perl示例:
use JSON;
my @ls_output = `ls`; ## probably better to use a perl module to do this, like DirHandle
print encode_json( @ls_output );
#11
-1
Should be pretty easy.
应该很容易。
$ cat ls2json.bash
#!/bin/bash
echo -n '['
for FILE in $(ls | sed -e 's/"/\\"/g')
do
echo -n \"${FILE}\",
done
echo -en \\b']'
then run:
然后运行:
$ ./ls2json.bash > json.out
but python would be even easier
但是python会更简单
import os
directory = '/some/dir'
ls = os.listdir(directory)
dirstring = str(ls)
print dirstring.replace("'",'"')