Eddie Jaoude Eddie Jaoude - 1 month ago 6
Bash Question

Flattern sub dirs & prepend file name with dir name using bash

This works:

ls -SF data/*/*/* | xargs -I % cp % migrations/db.tmp/


But I wish to prepend the filename with the directory name"
e.g.

data/folder1/subfolder1/file1.js -> data/folder1-subfolder1-file1.js


The next step I tried is:(but could not get it to work)

ls -SF migrations/db/*/*/* | xargs -I % cp % migrations/db.tmp/$(basename %)-%


Any ideas?

Answer

Don't use ls, especially with the -F option:

cd data
for f in */*/*; do cp "$f" "${f//\//-}"; done

Here's a much trickier method

cd data
printf "%s\n" */*/* | sed 'h; s,/,-,g; x; G; s/\n/ /; s/^/cp /'

That will output a bunch of cp commands. Pipe into | sh to execute them.