0

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.

0

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.

1

In the special case where the directory is the parent directory you can use rename/prename[1] from the parent directory to move the files to that parent directory:

rename -n 's:/:-:g' */file.txt

(-n is for dry runs, remove it or replace by -v for actual execution)

If the .txt files are several levels deep (or at an unknown depth), you can use the globstar option:

shopt -s globstar  # makes '**' match any levels of directories
rename -n 's:/:-:g' **/*.txt

[1] The command is rename on Debian/Ubuntu and derivatives, and prename on Redhat/Fedora and derivatives

0

I'm not entirely sure why you're using cat FIM_1.txt as this is a file you've not told us about. This code will copy file.txt from each of a set of folders and place in in the directory X named as the folder from which it came.

cd "$insub_FIM_M_1"
for DIR in *
do
    test -d "$DIR" -a -f "$DIR/file.txt" || continue
    mv -f "$DIR/file.txt" "/path/to/X/$DIR"
done
  • Why not loop over */file.txt? – Kusalananda Sep 13 '18 at 13:00
  • @Kusalananda no particular reason. Maybe because two years ago I didn't think of using "${path%/file.txt}" or equivalent expresssions? – roaima Sep 13 '18 at 16:08
0

I tried the following code and it worked:

 #!/bin/bash   
insub_FIM_M_1=path to a parent folder conatin all the folders (A,B,C,D,E,F,G,H) 
out=path 
for i in $(cat $insub_FIM_M_1/FIM_1.txt); do
cp  insub_FIM_M_1/file.txt ${path}/${i}.txt
done
  • 1
    Having a #! in the middle of the code makes no sense. The two characters #! needs to be first ones in the file. – Kusalananda Sep 13 '18 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy