I have a directory named data. Inside data there is one directory samples which has more than 50 directories and there is one shell script testing.sh inside data. The setup looks like below:

  |___ samples
         |______ PREC001
         |______ PREC003
         |______ PREC023
         |______ KRES118
         |______ TWED054
         |______ PREC098
  |___ testing.sh

I want to create a .txt file with the path for testing.sh for all the directories in the samples and also the directory names. I am working on linux.

The created .txt file should look like below:

/data/testing.sh PREC001 samples
/data/testing.sh PREC003 samples
/data/testing.sh PREC023 samples
/data/testing.sh KRES118 samples
/data/testing.sh TWED054 samples
/data/testing.sh PREC098 samples

How to do that in linux. I actually tried with some basic commands but I couldn't get what I want. Thankyou.


It should just be a matter of:

(cd data/samples && printf '/data/testing.sh %s sample\n' *) > file.txt

Or to restrict to files of type directory only, with zsh:

printf '/data/testing.sh %s sample\n' data/samples/*(/:t) > file.txt

Note that it also has the advantage of reporting an error and not clobbering file.txt if no matching file can be found.

Replace (/:t) with (-/:t) to also include files of type symlink that eventually resolve to a file of type directory.

If that's to generate shell code to be interpreted by sh later, you'd also want to make sure the names of the files are properly quoted. You could replace %s with %q for that, but then you'd need to make sure the script is interpreted by zsh instead of sh as %q could use some form of quoting that are specific to zsh.

Another alternative is to use the qq parameter expansion flag that always uses single quotes for quoting which are the most portable and safest quoting operators:

() {
  printf '/data/testing.sh %s sample\n' ${(qq)@}
} data/samples/*(/:t) > file.txt

If I understand you correcly, you can do this:

cd /pathto/data/samples || exit

for d in */; do
  echo "/data/testing.sh ${d: 1:-1} samples" >> /pathto/file.txt

$ cat file.txt
/data/testing.sh REC001 samples
/data/testing.sh REC003 samples
/data/testing.sh REC023 samples

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.