Add foldername as prefix to files

Hi there,
I am looping through folders in order to rename the files in the current folder.
So, given me being a newbie here, I would do that with a for-loop. The renaming per se should be like this:
I want to add the folder-name as a prefix to the files in the folder in question. For instance, looking at the folder 'ABCD' with the files E.fq, F.fq, and G.fq; these files should be renamed:
ABCD.E.fq, ABCD.F.fq, and ABCD.G.fq.

Feedback is greatly appreciated.

jahn

for i in /home/user/ABCD/*
do
FNAME=$(basename ${i})
FPATH=$(dirname ${i})
DNAME=${basename ${FNAME})
mv ${i} ${FPATH}/${DNAME}.${FNAME}
done
1 Like

Try:

for file in /path/to/your/directory/*
do
  fname=${file##*/} #This gives your base filename.
  fpath=${file%/*} # Your dir
  dname=${fpath##*/}
  mv $file ${fpath}/${dname}.${fname}
done
1 Like

Try this one also :-

cur_dir=`pwd`
for loop_dir in `ls -altr | awk '{if($9!="." && $9!=".." && $9!="")print $9}'`
do
cd $cur_dir
if [ -d $loop_dir ] ; then
cd $cur_dir/$loop_dir 
for loop_files in `ls -altr | awk '{if($9!="." && $9!=".." && $9!="")print $9}'`
do
if [ -f $loop_files ] ; then
mv $loop_files $loop_dir.$loop_files
fi
done
fi
done
1 Like

Thanks to all of you. Just wanted to show you what I ended up with:

for i in $(ls); do                        # runs through the 'items' in this dir                               
  if [ -d $i ]; then                      # if this is a dir
     fname=${i##*/}                 # pick up the dir name which will be used as prefix
     echo $fname                           
     cd $i                                    # move into the dir       
     for z in test*.fq; do               # loop over files starting with test and fq extension
       echo $z  
       cp $z ${fname}.${z}         # put the prefix to the file.               
     done                                        
     cd ..                                         
  fi                                              
done

If you're happy with the solution, fine. You should make sure that neither directories nor file names will contain spaces breaking the for loops, and you should be aware that cp will not rename the files as requested but produce new files with the prefixed names along with the old ones.

Always happy to learn new stuff. As I indicated, I am pretty much a newbie.