问题
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"
]
The only thing I could figure out is this:
ls mydir | jq -sR '[split("\n")[]|select(.|length>0)]'
[
"file1",
"file2",
"file3"
]
Is there a better way?
回答1:
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
Use the native shell printf
to separate entries on \0
and delimit it back
printf '%s\0' * | jq -Rn 'inputs | split("\u0000")'
or for just files
for file in *; do
[ -f "$file" ] && printf '%s\0' "$file"
done | jq -Rn 'inputs | split("\u0000")'
回答2:
Using find
opens up other possibilities:
find . -type f -maxdepth 1 -print0 |
jq -Rs 'split("\u0000") | map(sub("./";""))'
来源:https://stackoverflow.com/questions/65290874/read-raw-input-lines-and-output-single-array