How to cut out first last n characters from each file name, from a filelist How to cut out first n characters from a list of filenames / remove first three characters from a list of filenames / How to cut out last n characters from a list of filenames / remove last three characters from a list of filenames
Based on the comment posted by a visitor on How to remove first/last character from a string using SED article, I decided to create this simple example in which I will remove the first three characters from each file from a filelist.
Removing the first three characters from each file from a filelist
$ touch kkt.asdf $ touch tre.gsew $ touch oir.acr $ ls -a kkt.asdf oir.acr tre.gsew
At this point, the files are created in the curent working directory. Following command will list all files and, for each file, a new variable ($file_new) will take the value of the name of the file, without the last three characters:
$ ls | while read file; do file_new=`echo "$file" | sed 's/...\(.*\)/\1/g'`; mv "$file" "$file_new"; done
and now, that all files were renamed (moved) so that the first three characters were removed:
$ ls -a . .. .acr .asdf .gsew
(the order has changed because it is alphabetical)
P.S.: I advise you to test this before you try it AND carefull if you run it as root (and where you run it).
P.S.2: it can be modified so that it handles files in other directory than CWD and it can also be modified to remove the last three...four... characters.
Designed and developed by Andrei Manescu. Optimized for Mozilla Firefox.
Copyright 2007 Andrei Manescu
All trademarks and copyrights on this page are owned by their respective owners. Comments are owned by those who posted them.