# Ubuntu – Copy files of same name into same directory

bashcommand linecopyfiles

I have a large number of folders with a file named genome.txt that I need to cp into the same folder. I am trying to figure out how I can do this so the files look like genome1.txt, genome2.txt, etc.. I am looking for a simple solution to this.

### Shell script and its usage

This can be done with a simple shell script which makes use of find ...|while read var ; do ... done structure ( very common in dealing with filenames ). The bash script below operates on current (top-most) directory and takes single argument for destination.

#!/bin/bash
find -name "genome.txt" -print0 | while IFS= read -r -d '' path
do
base=$(basename --suffix=".txt" "$path")
new_path="${1%/}"/"$base"$counter".txt" echo "$path" "$new_path" counter=$(( $counter +1 )) done  >>>NOTE<<<: script uses echo just for testing purposes. When you are satisfied with resulting paths, replace echo with mv to move all filenames or cp to copy all filenames. Example: bash-4.3$ tree
.
├── destination
├── dir1
│   └── genome.txt
├── dir2
│   └── genome.txt
├── dir3
│   └── genome.txt
└── move_enumerated.sh

4 directories, 4 files
bash-4.3$./move_enumerated.sh ./destination ./dir2/genome.txt ./destination/genome.txt ./dir3/genome.txt ./destination/genome1.txt ./dir1/genome.txt ./destination/genome2.txt  ### Improving the script for more flexibility This script can be further improved to make it more general, where user can specify filename , top directory to traverse, and destination all as command-line arguments: #!/bin/bash find "$2"  -name "$1" -print0 | while IFS= read -r -d '' path do base=$(basename --suffix=".txt"  "$path") new_path="${3%/}"/"$base"$counter".txt"
echo "$path" "$new_path"
counter=$(($counter +1 ))
done


Test run: