'Linux bash command -backup=numbered. Put the number BEFORE the file extension

Using a one-line bash command with GitBash on windows, using find and cp, I am backing up a bunch of script files that exist in multiple sub-directories. I am currently backing them up to a single directory. As you can imagine, naming conflicts arise. This is easy enough to avoid with the --backup=numbered option which creates a copy of the file. However, the problem with this is that it puts the number AFTER the file extension, naming the file like this: example.js.~2~. What I want is to preserve the file extension and name the file like this: example2.js rather than putting the number after the file extension. Is there any way to do this?

Another option would be to prepend the directory name (from the directory that it is being copied from) to the file that is being copied instead of adding a number. I would accept either of these as a solution.

Here is what I have so far:

find . -path "*node_modules*" -prune -o -type f \( -name '*.js' -or -name '*.js.map' -or -name '*.ts' -or -name '*.json' \) -printf "%h\n" -exec cp {} --backup=numbered "/c/test/" \;

Any help would be appreciated! Thank you!



Solution 1:[1]

what about :

#!/bin/bash

# your find command here
FILES=$(find . -type f .....)

# loop through files and create a new filename with the path within ( slashes replaced by underscores
for FILE in $FILES; do
    NEW_FILENAME=$(printf "%s" "$FILE" | sed s/\\//_/g)
    cp "$FILE" "/c/test/${NEW_FILENAME}"
done

from your question, I am unsure if a one liner is mandatory...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fun_times