I have multiple unique directories that each contain a file named filtered_feature_bc_matrix.h5. I want to paste the directory-name onto the filename to make the filename unique within each folder. Is this possible?
./sample_scRNA_unsorted_98433_Primary_bam/outs/filtered_feature_bc_matrix.h5
./sample_scRNA_unsorted_77570_Primary_bam/outs/filtered_feature_bc_matrix.h5
out:
./sample_scRNA_unsorted_98433_Primary_bam/outs/sample_scRNA_unsorted_98433_Primary_bam_filtered_feature_bc_matrix.h5
./sample_scRNA_unsorted_77570_Primary_bam/outs/sample_scRNA_unsorted_77570_Primary_bam_filtered_feature_bc_matrix.h5
CodePudding user response:
For completeness here is a solution with only bash built-in:
shopt -s globstar nullglob
name="filtered_feature_bc_matrix.h5"
for f in */**/"$name"; do mv "$f" "${f%/*}/${f%%/*}_$name"; done
CodePudding user response:
find . -type f -name 'filtered_feature_bc_matrix.h5' \
-exec sh -c \
'fp="$1"; d=$(echo "$fp"|cut -d/ -f2); echo $(dirname "$fp")/${d}_$(basename "$fp")' \
-- '{}' \;
findallows to iterate the files with relative path-execallows to do action on'{}'which is the file pathshis used to simplify the actiondirnameandbasenameallows to extract directories or filename.cutis used to extract only the first directory (second field as the first one is.)
To rename:
find . -type f -name 'filtered_feature_bc_matrix.h5' \
-exec sh -c \
'fp="$1"; d=$(echo "$fp"|cut -d/ -f2); mv -v "$fp" "$(dirname "$fp")/${d}_$(basename "$fp")"' \
-- '{}' \;
