The question is published on by Tutorial Guruji team.
I have a sort of folders (A,B,C,D,E,F,G,H) and I have one file in every folder has the same name in all the folders (file.txt) but the size of this file is different from folder to folder. I wanted to copy this file from every folder into a new folder (X) and give the file the same name of it is original folder. I used this bach script to copy the files:
#!/bin/bash insub_FIM_M_1=path to a parent folder conatin all the folders (A,B,C,D,E,F,G,H) for i in $(cat $insub_FIM_M_1/FIM_1.txt); do cp insub_FIM_M_1/${i} <path to the new folder X > done
In this code all the files will ovewrite in the new folder (X) because they have the same name inside the folders. How can I revise this code to add the folder name to the file name so I can know the source of the file.
Answer
Assuming that your subdirectories are located in $insub_FIM_M_1
and that the file that you want to copy is called file.txt
in each of those subdirectories, then
mkdir -p result || exit 1 for pathname in "$insub_FIM_M_1"/*/file.txt; do cp "$pathname" "result/$( basename "$( dirname "$pathname" )" )_file.txt" done
would copy these files to the result
directory in the current directory while renaming each file according to the directory that they are located in.