read raw input lines and output single array

此生再无相见时 提交于 2021-01-28 22:40:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!