0

So I want to grab all certain files then duplicate them in the same folder/location but with a different extension. So far I have this from another question Copy all files with a certain extension from all subdirectories:

find . -name \*.js -exec cp {} newDir \;

I want to duplicate all those .js files into .ts e.g. duplicate functions.js to functions.ts wherever it may be.

more examples:

a/functions.js
b/test.js
c/another.js
index.js

to

a/functions.ts
b/test.ts
c/another.ts
index.ts
A. L
  • 11,695
  • 23
  • 85
  • 163

2 Answers2

2
find . -name \*.js | while read jsfile; do cp "${jsfile}" "${jsfile%.js}.ts"; done
  1. find . -name \*.js list all .js files
  2. using read command to read each line from the output of fine command.
  3. ${jsfile%.js} means to remove the suffix .js from variable jsfile, for example, a/functions.js will become to a/functions
Feng
  • 3,592
  • 2
  • 15
  • 14
  • Could you write an explanation about what each part is doing? The answer is correct though. – A. L Sep 13 '18 at 03:10
1

Here is how to assign variables using find and xargs and open up all sort of command-line options,

$ find . -name '*.js' | xargs -I {} bash -c 'p="{}"; cp $p newDir/$(basename ${p%.js}.ts)'

Use xargs -I {} to get the output of find as input to xargs. Use bash -c to execute a command.

Here is a demo:

$ mkdir -p a b c d newDir
$ touch a/1.js b/2.js c/three.js d/something.js
$ find . -name '*.js' | xargs -I {} bash -c 'p="{}"; cp $p newDir/$(basename ${p%.js}.ts)'
$ ls newDir/
1.ts        2.ts        something.ts    three.ts

EDIT (Question changed after hours of initial post). To keep a duplicate in the same directory use the same cp command and remove newDir and basename:

$ find . -name '*.js' | xargs -I {} bash -c 'p="{}"; cp $p ${p%.js}.ts'
iamauser
  • 11,119
  • 5
  • 34
  • 52
  • To clarify, that command was an example from the other question, I want the output to remain in their respective folders. I have added a more detailed example to my question, thanks. – A. L Sep 13 '18 at 03:05
  • see my updated comment. Fairly simple modification to my original answer would get you the result you want. – iamauser Sep 13 '18 at 13:52