Home > other >  How can i copy all the files in a folder and change the name in the same directory?
How can i copy all the files in a folder and change the name in the same directory?

Time:04-19

i am having trouble trying to copy all the numbered files in a directory and change their names in the same directory but with same number, i am trying to do this:

cp rj1.text mike1.text
cp rj2.text mike2.text
cp rj3.text mike3.text
cp rj4.text mike4.text
cp rj5.text mike5.text
cp rj6.text mike6.text 

this is the code i tried using

cp /home/ryan/Desktop/rj/"rj*.text" /home/ryan/Desktop/rj/"mike*.text"

CodePudding user response:

Since this is tagged [bash] you can use a simple parameter expansion with substring replacement to loop over the files replacing "rj" with "mike" as you copy each file.

For example You can do:

for f in *; do 
  cp "$f" "${f/rj/mike}"
done

(note: if you have more than just the "rj" files in the directory, you can replace the * glob with rj[[:digit:]].text to only match files with "rj" followed by a single-digit and the .text. Or, to just match digits 1-6, you can use rj[123456].txt or rj{1..6}.txt, up to you. The [123456] will work with all POSIX shells, the brace-expansion {1..6} is bash only)

Example Use/Output

Change to an empty directory and create the six file with "rj" in the name:

touch rj{1..6}.text

Now copy and change the name using the command above. The result you are wanting is now in the directory with both the "rj" and "mike" copies of the files, e.g.

$ tree
.
├── mike1.text
├── mike2.text
├── mike3.text
├── mike4.text
├── mike5.text
├── mike6.text
├── rj1.text
├── rj2.text
├── rj3.text
├── rj4.text
├── rj5.text
└── rj6.text

(note: to move the files from "rj" to "mike" removing the "rj" files, just use the mv command instead of cp)

CodePudding user response:

I can only think of a multi-step process:

mkdir tmp
cd tmp
cp ../rj*.text ./
rename rj mike *.text
cp ./* ..
cd ..
rm -rf tmp
  •  Tags:  
  • bash
  • Related