Skip to content
Advertisement

Remove part of file name in multiple sub directories

The main folder “Main” contains multiple subfolders (6900,159, 9997, …) and each subfolder contains 8 items (4 files (6900Log.final.out, 6900Log.out, 6900Log.progress.out, 6900SJ.out.tab), 3 folders (6900_STARgenome, 6900_STARpass1, 6900_STARtmp), and one compressed file (6900Aligned.sortedByCoord.out.bam)). The 6900_STARtmp contain further subfolders but I don’t want to change name of sub folders present in 6900_STARtmp. Please see the image

see Image

I want to remove 6900 from (6900Aligned.sortedByCoord.out.bam, 6900Log.final.out, 6900Log.out, 6900Log.progress.out, 6900SJ.out.tab) and 6900_ from (6900_STARgenome, 6900_STARpass1, 6900_STARtmp)

So that the names of files should be (Aligned.sortedByCoord.out.bam, Log.final.out, Log.out, Log.progress.out, SJ.out.tab, STARgenome, STARpass1, STARtmp).

I have tried to run the below script on ubntu (18.04.3 LTS) to rename SJ.out.tab and was planning to do it for rest of files but it didn’t work for me:

for filename in Main/*/*SJ.out.tab; do 
    #echo $filename
    describer=$(echo ${filename})        
    #mv "$filename" "${filename//${describer}/SJ.out.tab}"
done

Any help will be highly appreciated.

Advertisement

Answer

To make sure you do not accidentally modify other files or directories, you should make sure your script restrict itself to ONLY files staring with the same digits as the directory name or directories starting with the number and an underscore, and ONLY one layer deep.

Try this:

#!/bin/bash

declare    base_dir=/path/to/Main

cd ${base_dir}
while read subdir; do
  number=${subdir#./}
  for file in $(find ${subdir} -maxdepth 1 -type f -name "${number}*"); do
    mv ${file} ${subdir}/${file##./${number}/${number}}
  done
  for file in $(find ${subdir} -maxdepth 1 -type d -name "${number}_*"); do
    mv ${file} ${subdir}/${file##./${number}/${number}_}
  done
done < <(find . -maxdepth 1 -type d -regex './[0-9]*')
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement