2

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?

2
  • What are you looking to do with the array? Commented Dec 14, 2020 at 14:51
  • i am merging the contents of each file in that directory. each file is known as a dataset. the dataset name is the filename. so, once these files are merged, i am injecting metadata into that merge which declares which datasets comprises this merge. that injection is this array. so, two things. merging contents, injecting dataset origin metadata. the files have all been created by me, they have predictable filenames. Commented Dec 14, 2020 at 17:10

3 Answers 3

2

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")'
Sign up to request clarification or add additional context in comments.

1 Comment

ls mydir | jq -nR '[inputs]'
1

Using find opens up other possibilities:

find . -type f -maxdepth 1 -print0 |
  jq -Rs 'split("\u0000") | map(sub("./";""))'

1 Comment

thanks @peak, the inputs is what was illuding me.
0

This works. Slightly simpler than what you have:

ls mydir | jq -sR 'split("\n")[0:-1]'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.