|
Author |
Message |
|
|
Posted : Tue, 22 April 2008 13:26:09
Subject :
Bash script help
I need a bash script to loop through a directory and do a filename change on each item: specifically on each file remove the last character prior to the extension. i.e. file1a.txt becomes file1.txt - The logic of accomplishing this escapes me. Or, is there a way to do this with mmv? The looping is no problem, it's zapping that last pre-extension character.
Thanks!
|
|
|
|
Shashank Sharma
|
Posted : Mon, 28 April 2008 17:48:45
Subject :
Bash script help
Is there any order to the file names? I mean, do all files have 5 character names, and you want to drop the fifth character? Do all files have same extension (or same length extension, like .jpg, .txt, .png, .mpg)? Is the character to be removed the same for all files?
This link might give you some ideas:
http://www.ivorde.ro/How_to_remove_first_last_character_from_a_string_using_SED-75.html
|
|
linuxdynasty
|
Posted : Tue, 29 April 2008 04:03:36
Subject :
Re: Re: Re: Re: Re: Bash script help
I can not help you with a shell script but I can help you do it in python script..
I will post this on my site as well.
You can check it out here http://linuxdynasty.org
[code=xml]#!/usr/bin/env python
import os, re, sys
os.chdir(sys.argv[1])
ls = os.listdir('./')
for file_o in ls:
file_n = re.sub("\w\.", ".", file_o)
os.rename(file_o, file_n)
print os.listdir("./")
[/code]
[Modified by: linuxdynasty on April 28, 2008 11:26 PM]
[Modified by: linuxdynasty on April 28, 2008 11:43 PM]
[Modified by: linuxdynasty on April 28, 2008 11:44 PM]
[Modified by: linuxdynasty on April 29, 2008 12:58 PM]
|
|
xi
|
Posted : Fri, 02 May 2008 03:59:42
Subject :
Re: Bash script help
[code=xml]for i in *.* ; do
extension="${i##*.}"
newname="${i%?.*}"
mv "$i" "$newname.$extension"
done[/code]
|
|
Vassil Dichev
|
Posted : Fri, 02 May 2008 08:25:00
Subject :
Bash script help
As Larry Wall said, There's More Than One Way To Do It (you'll see it often as TMTOWTDI). So here's my version:
Some distributions have a "rename" utility. The problem is, it's not very consistent across distributions: some don't have it and some have a different syntax. Debian-based distributions (including Ubuntu) have the more powerful regular expression syntax, which you can use:
rename 's/(.*).\.(.+)/$1.$2/' *
Test with the "-n" option first to just see what would be done.
If you cannot have that, the simplest thing I could use is "sed". First verify if it works right, because the regular expression can get hairy:
ls | sed "s/\(.*\).\.\(.\+\)/mv \0 \1.\2/"
Then if you're sure of the result, execute it by piping to "sh":
ls | sed "s/\(.*\).\.\(.\+\)/mv \0 \1.\2/" | sh
|
|
jeffelkins
|
Posted : Mon, 05 May 2008 17:08:52
Subject :
Re: Bash script help
Thanks for the replies! I used the bash solution but all were interesting and educational.
Jeff
|