cutting the last N characters form a file name
Hello,
I'm writing a bash script and I would like to do the following: I have a directory with the following: file001.jpg file002.jpg file003.jpg Now i want a bash script that can give 'file' back to me. The command: 'cut -c 1-4' doest work for me, cause i also want the same to work on otherfile001.jpg otherfiie002.jpg otherfile003.jpg So what i'm looking for is a command that can strip the last 7 characters for me. Anyone know how this can be done? Thanks, Rindert |
can i suggest using basename instead?
Code:
# basename /root/test.txt .txt |
How about this?
Code:
ada@barnabas:~> ( filename=otherfile002.jpg; echo ${filename/%???.jpg}) |
Quote:
Code:
# echo test.txt | cut -d. -f1 |
But Rindert's trying to remove the last 7 characters which consist of varying digits and the extension .jpg. That's why basename won't work.
|
The best (and easy) approach is to remove 7 characters (xxx.jpg) from the BEGINNING of the string. The command 'rev' is handy in this case.
Code:
$ echo otherfile001.jpg | rev | sed -e 's/.......//' | rev |
Of course, if you like cut, ou can use 'cut -c 8-', instead sed.
Code:
$ echo otherfile001.jpg | rev | cut -c 8- | rev |
best?? pah, not even close... :)
|
Ok, not "The Best", but how about the "easy" part ? :)
Cheers, |
easy? piping through 3 commands when 1 will do? keep trying :)
|
Hey acid_kewpie !
All right, I will never more use the words "best" and "easy" in a post, specially if you are subscribed to it ;) cheers, |
Hello,
I've tried the ( filename=otherfile002.jpg; echo ${filename/%???.jpg}) command, it does work on the shell, but how can i use it in my bash script? I have to use it for mutpiple dirs so i think best way i to use with 'ls' right? But how do I get the result from 'ls' in the filename variable? I'm kinda new to shell scripting. This is my first own script I'm writing. Because I'm a newbie to shell scripts. Let say I want the easiest way of doing it, it doesn't have to be best way, as long as it is a good way. Thanks, Rindert |
You could try something like
Code:
#! /bin/bash |
well it depends what your circumstances are, most of these ways will work, but do you have different length extensions? different test in extensions? if you do want to use that example there, then you'd simply replace "filename" in the echo part with the variable name you currently have the string assigned to. if you don't actaully want to echo it, but store it, then you'd do, for example:
Code:
original=test.txt |
I'v tried some things, and for me this works good:
cat_profile= ls -1 *001.jpg | rev | cut -c 8- | rev the result is get is: otherfile. just what i wanted :) thanks everyone for helping me :) |
All times are GMT -5. The time now is 12:46 PM. |