-1

I want a list of all files which are in various subfolders. Since subfolders are constantly added I need to update the list of subfolders automatically.

For the example I have added the subfolders html,pdf,md.

#!/bin/zsh
# I get all the subfolders of the folder DIR automatically as a list.
folder=$(ls -l DIR/ | awk '/^d/ { print $9 }' | tr '\n' ',' | sed 's/,$//g' )
echo "Folder: $folder"
# --> html,md,pdf

# Now get the files of the found subfolders
files=$(ls -m DIR/{$folder}/*)
echo "Files: $files"
# DOES NOT WORK

# this works instead:
ls -m DIR/{html,md,pdf}/*

Putting in the subfolder’s names manually in the ls-command works fine.

The output I am hoping to get back from $files is (example):

DIR/html/dataStorage.html, DIR/md/dataStorage.md, DIR/pdf/data.pdf, DIR/pdf/dataStorage.pdf

I am using zsh.

lukascbossert
  • 375
  • 1
  • 11
  • 1
    Please note: [Why *not* parse `ls`?](http://unix.stackexchange.com/questions/128985/why-not-parse-ls) – Cyrus Jun 28 '20 at 09:17
  • @LukasCB : Note that you get the list of all subfolders of `DIR` by `DIR/*/(D)`. Try for instance `echo DIR/*/(D)`. – user1934428 Jun 29 '20 at 11:03

2 Answers2

0

You don't need a comma-separated list (which wouldn't be of much use if an element can contain a comma) when you have proper arrays.

Using brace expansion to create three separate globs to expand

files=(DIR/*/*.{html,md,pdf})

or using the KSHGLOB option to create one glob

setopt KSHGLOB
files=(DIR/*/*.@(html|md|pdf))
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks for your answer. But it takes into account that I *already know* the name of the subfolders. I was interested in getting the files of the subfolders which I do not know (and want to type in manually). – lukascbossert Jun 29 '20 at 07:04
  • Nothing here assumes the names of the subfolders. `DIR/*/` matches the subfolders; `DIR/*/*.html`, e.g., matches the files with the `.html` extension in each of those subfolders. – chepner Jun 29 '20 at 11:54
-1

I found a solution. All files in all subfolders are automatically found. No need to check for subfolders first.

files=$(ls -R DIR | awk '
  /:$/&&f{s=$0;f=0}
  /:$/&&!f{sub(/:$/,"");s=$0;f=1;next}
  NF&&f{ print s"/"$0 }' | tr '\n' ',' | sed 's/,$//g' )

It is based on https://stackoverflow.com/a/1767559/8584652 and slightly modified (piping to tr and using sed in the end).

lukascbossert
  • 375
  • 1
  • 11