Bash newbie here trying to insert the name of a folder into certain files inside that folder.
The problem is that these files are in subfolders of subfolders of the main directory, and the names of each level are different in each case.
For example, the main folder interviews
may contain John Doe
and under John Doe
is a directory Images
with a file Screenshot.jpg
. But there might also be John Smith
with a folder Etc
in which is 12_Screenshot 2.jpg
.
I want to rename all these files containing Screenshot
inserting John Doe
or John Smith
before the filename.
I tried adapting a couple of scripts I found and ran them from the interviews
directory:
for i in `ls -l | egrep '^d'| awk '{print $10}'`; do find . -type f -name "*Screenshot*" -exec sh -c 'mv "$0" "${i}${0}"' '{}' \; done
after which the terminal gives the caret prompt, as if I'm missing something. I also tried
find -regex '\./*' -type d -exec mv -- {}/*/*Screenshot* {}/{}.jpg \; -empty -delete
which returns find: illegal option -- r
The fact that the second one theoretically moves the file up to the parent folder is not a problem since I'll have to do this eventually anyways.
The following script will work as desired :
dir=$1
find $dir -name "*Screenshot*" -type f | while read file
do
base=$(basename $file)
dirpath=$(dirname $file)
extr=$(echo $file | awk -F/ '{print $(NF-2)}') #extracts the grandparent directory
mv $file $dirpath/$extr-$base
done
As @loneswap mentioned, this must be invoked as a script. So if your main directory is mainDir
, then you would invoke it as so...
./script mainDir