Larry Posted October 18, 2007 Share Posted October 18, 2007 OK, maybe there's somebody out there who'll know this. I'm looking for a Linux shell script that will allow me to truncate a file name. I just tried, on a test file, "mv ????* ????". but while the pattern "????*? matches all files with 4 or more characters in the name, the second pattern, "????" is interpreted literally, so rather than "leave the first 4 characters of the file name alone", I get "make the file name 4 question marks". I know enough to be able to use find to find files that are too long. But how do I tell it "when you find one, chop off the end of the file name"? Link to comment Share on other sites More sharing options...
Zuck Posted October 18, 2007 Share Posted October 18, 2007 I'm not great at shell scripting but I could show you how to do that in perl? Link to comment Share on other sites More sharing options...
JMS Posted October 18, 2007 Share Posted October 18, 2007 Try rename. mv copies the file to a new location, as well as renames them. What Linux Shell are you using and I can be more specific with my assistance. Bourne(BASH), , Korn (KSH), Born, C(CSH) or TCSH? try using rename cause rename just changes the name rather than move which copyies the contents, deletes the source, and renames the file. Also you could try not using spaces in your file names on the command line that might be confusing. rename h?pe.txt hope.txt Link to comment Share on other sites More sharing options...
Zuck Posted October 18, 2007 Share Posted October 18, 2007 This will work in perl #!/usr/local/bin/perl use strict; my $dir = "put the directory you want to evalutate here"; opendir(DIRHANDLE,"$dir") || die; my @filenames = readdir(DIRHANDLE); foreach my $filename (@filenames){ $filename =~ /(.{5})*/i; if (defined $1){ system "mv $filename $1"; } } Link to comment Share on other sites More sharing options...
Larry Posted October 18, 2007 Author Share Posted October 18, 2007 1) I'm using BASH 2) My problem seems to be that commands like mv all take arguments like <from> <to>. And I don't have a way to say "<to> = <the first 25 characters of <from>>" find will give me an argument that contains the entire name of the file. But I need, as an argument to my command, PART of that argument. Link to comment Share on other sites More sharing options...
JMS Posted October 18, 2007 Share Posted October 18, 2007 If $a holds your file name this will chop off the first four characters of that name and return them in $b. # substr: extract substring, starting position & length specified b=`expr substr $a 1 4` echo "Substring of \"$a\", starting at position 1,\ and 4 chars long is \"$b\"." Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.