Search code examples
jsonjqls

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

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?


Solution

  • 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")'