0

I have a script that rename all the files from .txt to .txt2. I want to do the same thing but in all the subdirectories.

This is my code.

rename 's/.txt/.txt2' *.txt
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
agm_2502
  • 13
  • 3

2 Answers2

0

Like this using Perl's rename:

shopt -s globstar # bash specific, enabled by default in `zsh`
rename 's/\.txt$/\.txt2/' ./**/*.txt
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
-2

I found the answer, but it's hardly readable.

for filePath in $(find . -name "*.txt"); do filePathWithoutExtension=$(echo ${filePath} | head -c -4) && mv ${filePath} ${filePathWithoutExtension}txt2; done
```

Before :
````bash
tree
.
├── folder1
│   ├── foo.txt
│   ├── subfolder1
│   │   └── foo.txt
│   └── subfolder2
│       └── foo.txt
├── folder2
│   └── foo.txt
└── foo.txt

4 directories, 5 files

After :

tree
.
├── folder1
│   ├── foo.txt2
│   ├── subfolder1
│   │   └── foo.txt2
│   └── subfolder2
│       └── foo.txt2
├── folder2
│   └── foo.txt2
└── foo.txt2

4 directories, 5 files
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • This is bad code. Don't handle files with spaces or other special characters, and variables non properly quoted. **Don't use this!** Asked you `ChatGPT` to create this horrible snippet? It's works here, because you have simple files, but in `RealLife©®™` it will break – Gilles Quénot Mar 14 '23 at 10:30