Hopefully such a thing is possible, I would like to scan all the files in the subfolders of

/home/user/source/

and create symlinks to these files in a different folder with a different file extension. So I start with this folder structure:

/home/user/source/folder1/random_file_name.bin
/home/user/source/folder2/random_file_name.bin
/home/user/source/folder3/random_file_name.bin
...

And I would like to create symlinks to the bin files like such:

/home/user/dest/folder1.txt -> /home/user/source/folder1/random_file_name.bin
/home/user/dest/folder2.txt -> /home/user/source/folder2/random_file_name.bin
/home/user/dest/folder3.txt -> /home/user/source/folder3/random_file_name.bin
...

Can I do this in only one loop or must I scan each folder of "source" to extract the folder name then loop in each folder to find the bin file in each folder? There's only one bin file per folder, with a random name by the way.

Unless there is a way to do this with the "find" command?

  • What should happen if there's a second file in, say, folder1? – Eric Renouf Sep 17 '17 at 14:59
  • I have no idea, I don't know if it can even happen. I guess the files of "folder1" would be in alphabetical order so the last one scanned would overwrite the symlink with -sf parameter, which is fine since the files contain a timestamp in the name – NaturalBornCamper Sep 18 '17 at 2:51
up vote 1 down vote accepted
for d in $(find source -type d); do ls $d/*.bin 1>/dev/null 2>&1 && ln -s $d/*.bin target/$(basename $d).dat;done

In slow-mo:

  • Scan for the directories
  • if the directory contains at least one .bin file
  • link the bin file using the directory name
  • Wow all in one line thanks! And +1 for the explanations :) – NaturalBornCamper Sep 18 '17 at 2:51
  • This won't work if any of the directories contain spaces or other characters in IFS so be careful with this sort of answer – Eric Renouf Sep 18 '17 at 2:54

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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