1

I have multiple sub folders e.g.:

ls ./
F1 F2 F5 F8 F12 ...

Each folder contain file "file.txt"

How to copy all file.txt files to main folder containing folder name?

cp ./F1/file.txt ./file_1.txt
cp ./F2/file.txt ./file_2.txt
...
Pasi
  • 181
  • 2
  • 7

3 Answers3

2

Perl One Liner

first go to main folder than:

find . | perl -a -F/ -lne 'qx(cp -r "$F[1]" T/ )'

note
do not worry about log file on the screen if would be!
T/
is your target directory
main folder
Where all your file exist. If your all file is in the folder Music for example; so cd Music then that Perl One Liner

Shakiba Moshiri
  • 21,040
  • 2
  • 34
  • 44
1
declare -a dirs
i=1
for d in */
do
    dirs[i++]="${d%/}"
done
echo "There are ${#dirs[@]} dirs in the current path"

for((i=1;i<=${#dirs[@]};i++))
do
    echo "Copying file.txt from ${dirs[i]} dir..."
    cp ./${dirs[i]}/file.txt ./file_$i.txt
done

Save it as a script file, fileTxtCopy.sh, for instance. Then place it at the parent dir and give it executable permission sudo chmod +x fileTxtCopy.sh.

Run it as script and you should have all your file.txt file copied in parent dir.

fluffyBatman
  • 6,524
  • 3
  • 24
  • 25
0

Copies file.txt files from each folder inside a current directory to the current directory and appends numbers contained in a folder name to the name of the copied file.

for i in *; do a=$(<<< "$i" grep -o "[0-9]*" -); cp "$i/file.txt" "file_$a.txt"; done

Not the most robust approach though.

anfauglit
  • 161
  • 1
  • 6