27

we want to replace the script file extension

so we did the following:

 new_name=` echo run_fix.bash  |  sed 's/[.].*$//' `
 new_file_extension=".in_hold.txt"
 new_name=$new_name$new_file_extension

 echo $new_name
 run_fix.in_hold.txt

but I feel my approach is not so elegant

note - because script extension could be bash or perl or python and also the target extension could be any thing after "." we want global replacement


I am using redhat 7.2

1
  • 1
    Don't give scripts file-name-extensions: The caller should not need to know what language a script is written in. Instead, use #!… Dec 17, 2018 at 11:54

2 Answers 2

47
old_name=run_fix.bash
new_name=${old_name%.bash}.in_hold.txt

printf 'New name: %s\n' "$new_name"

This would remove the filename suffix .bash from the value of $old_name and add .in_hold.txt to the result of that. The whole thing would be assigned to the variable new_name.

The expansion ${variable%pattern} to remove the shortest suffix string matching the pattern pattern from the value of $variable is a standard parameter expansion.

To replace any filename suffix (i.e. anything after the last dot in the filename):

new_name=${old_name%.*}.new_suffix

The .* pattern would match the last dot and anything after it (this would be removed). Had you used %% instead of %, the longest substring that matched the pattern would have been removed (in this case, you would have removed everything after the first dot in the string). If the string does not contain any dots, it remains unaltered.

1
  • 1
    I upvoted this answer because although I knew how to do this, I did not understand what was happening. You explain this clearly and concisely, with a link to further details. A model answer.
    – David
    Oct 28, 2020 at 17:06
0

Try the rename command, by larry wall. Not installed by default on all systems, and some have a different command with this name. It is definitely available for Debian based systems.

rename is sed for filenames.

2
  • It's more like Perl for filenames as as far as I can tell, you could put a whole perl program into a rename operation, given that you use the Perl implementation of rename.
    – Kusalananda
    Dec 17, 2018 at 11:55
  • 2
    @Kusalananda yes it is very flexible, but you can also just use it like sed (but for file-names). No need to scare people. Dec 17, 2018 at 11:57

You must log in to answer this question.

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