LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   making a bash script file (https://www.linuxquestions.org/questions/linux-general-1/making-a-bash-script-file-373494/)

Berticus 10-15-2005 10:17 PM

making a bash script file
 
I hope I'm calling it correctly...

Anyway, I'd like to know how to take off the extension of a file. For example, let's say I have something.txt and somethingelse.txt, how do I make a bash script to just look at it and see something and somethingelse? I've got the first part down:
Code:

#!/bin/bash

for i in *.txt; do
mv $i $i.yo
done

This would rename the files into something.txt.yo and somethingelse.txt.yo instead of something.yo and somethingelse.yo.

Dark_Helmet 10-15-2005 11:14 PM

There are a couple different ways, but I usually end up using sed.

For instance, try this on the command line:
Code:

$ echo "something.txt" | sed 's/\.txt$/.yo/'
Here's some of an explanation of what's happening:
sed looks at the input text ("something.txt" in this case) and tries to match ".txt" at the end of the input. Side note: the '\\' in front of the period with "txt" is necessary. If sed finds text that matches, it replaces that text with ".yo". For this case, the '\\' is not necessary for the period before "yo". The details of which are long. You should be able to read about why in the sed man page (man sed) or with a Google search about regular expressions.

Anyway, the point is, the output of that command gives you the name of the file with the extension replaced. The command will work with any extention - you just have to replace "txt" for the extension you want to match and "yo" with the extension you want to replace it with.

If you want to work it into your script as a learning exercise, I'll hold off on posting how to integrate it. If you just want to "get it to work" then say so, and I'll show you how I'd work the command in.


All times are GMT -5. The time now is 04:02 AM.