I found out that you can apparently add suffix on the fly, this is useful for me to disable a service that relies on the existence of file extension.
$ mv -v file.txt{,.bak}
renamed 'file.txt' -> 'file.txt.bak'
But how can one do the reverse ? What command I have to use ?
$ mv -v file.txt.bak{??}
renamed 'file.txt.bak' -> 'file.txt'
CodePudding user response:
Your command (mv -v file.txt{,.bak}
) relies on Bash brace expansion, which translates file.txt{,.bak}
to file.txt file.txt.bak
. Check out the Bash manpage section for "Brace Expansion". In this case ({,.bak}
), there are two strings in the comma-separated list: an empty string and .bak
. As such, you can add extensions and the like.
Several examples come to mind for removing extensions using brace expansions (all expanding to mv -iv file.txt.bak file.txt
):
mv -iv file.txt{.bak,}
f=file.txt.bak; mv -iv ${f%.bak}{.bak,}
, which doesn't presuppose the filename preceding the ".bak" extension (in the Bash manpage, see "Remove matching suffix pattern")f=file.txt.bak; mv -iv ${f%.*}{.${f##*.},}
, which doesn't presuppose any specific extension (in the Bash manpage, additionally see "Remove matching prefix pattern")
As an alternative, and as another contributor suggests, rename
is a useful and powerful utility (e.g., rename 's/\.bak$//' *.bak
).
P.S. Whenever documenting or scripting variabilized examples, I generally recommend quoting for whitespace safety (e.g., mv -iv "${f%.*}"{."${f##*.}",}
).
CodePudding user response:
why donot use rename
command.
rename '.bak' '' fileNames
CodePudding user response:
You can use:
file.txt{.bak,}
In this way you substitute the word before the comma with the empty string that is after the comma.