读取原始输入行并输出单个数组 [英] read raw input lines and output single array
问题描述
我有一个包含文件的目录.我想从该文件列表中创建一个数组.我认为这很容易,例如:
I have a directory with files in it. I would like to create an array from that list of files. I thought it would be pretty easy, like:
ls mydir | jq -R '[.]'
[
"file1"
]
[
"file2"
]
[
"file3"
]
我唯一能弄清楚的是:
ls mydir | jq -sR '[split("\n")[]|select(.|length>0)]'
[
"file1",
"file2",
"file3"
]
有更好的方法吗?
推荐答案
在处理Unix文件名时,您必须格外小心.它们几乎可以包含文件名中的任何字符,包括空格,换行符,逗号,管道符号,以及除NUL之外几乎所有您尝试用作定界符的其他任何字符.最好的选择是用NUL字符分隔名称,这是唯一不能成为有效文件名一部分的字符,并用jq
You'd have to be extra careful in dealing with Unix filenames in general. They can contain almost any character in a filename, including whitespace, newlines, commas, pipe symbols, and pretty much anything else you'd ever try to use as a delimiter except NUL. Your best bet is to separate the names with the NUL character, which is the only character that can't be part of a valid filename and split on it with jq
使用本机外壳printf
分隔\0
上的条目并将其重新定界
Use the native shell printf
to separate entries on \0
and delimit it back
printf '%s\0' * | jq -Rn 'inputs | split("\u0000")'
或仅用于文件
for file in *; do
[ -f "$file" ] && printf '%s\0' "$file"
done | jq -Rn 'inputs | split("\u0000")'
这篇关于读取原始输入行并输出单个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!