1

I have a project named my-project with the following file tree.

my-project/ (before)
.
├── src
│   ├── index.html
│   ├── main.js
│   ├── normalize.js
│   ├── routes
│   │   ├── index.js
│   │   └── Home
│   │       ├── index.js
│   │       └── assets
│   ├── static
│   ├── store
│   │   ├── createStore.js
│   │   └── reducers.js
│   └── styles
└── project.config.js

Now, I want to rename the following files to add the string -orig immediately before the filetype extension.

files-to-rename.txt
src/main.js
src/routes/index.js
src/store/reducers.js
project.config.js

(I do not want to change any of the file contents at all.)

So the final file tree looks like the following.

my-project/ (after)
.
├── src
│   ├── index.html
│   ├── main-orig.js
│   ├── normalize.js
│   ├── routes
│   │   ├── index-orig.js
│   │   └── Home
│   │       ├── index.js
│   │       └── assets
│   ├── static
│   ├── store
│   │   ├── createStore.js
│   │   └── reducers-orig.js
│   └── styles
└── project.config-orig.js

Is there a way to accomplish this with a single line or command?

0

4 Answers 4

4

In bash:

while read ; do mv "$REPLY" "${REPLY%.js}-orig.js" ; done < files-to-rename.txt
3

One approach would be to ask the shell to read each line from the file, then use shell parameter expansion to extract the base filename and the extension:

while IFS= read -r filename
do
  base=${filename%.*}
  extension=${filename##*.}
  echo mv -- "my-project/$filename" "my-project/${base}-orig.${extension}"
done < files-to-rename.txt

Remove the echo if the output looks correct.

1
for i in `cat files-to-rename.txt`; do postfix=${i/#*\./}; mv $i ${i/%.$postfix/-orig.$postfix}; done;

this works with arbitrary postfix, not just js. however, please use try git or svn for your own sake. even a tar command will work better than this.

1
  • The for i in `cat ...`thing will not work with filenames containing spaces. You'd need IFS='\n', or use read.
    – L. Levrel
    Nov 13, 2018 at 7:45
1

Using the rename command. First do a verbose test run that changes nothing:

rename -n -v 's/.js$/-orig.js/' $(find my-project/)

If that seems correct, remove the -n to actually rename the files:

rename    -v 's/.js$/-orig.js/' $(find my-project/)

Note: to install rename on a Debian or Ubuntu box, do:

apt install rename

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .