% perl -p -i -e 's/one/two/g' file
Wednesday, April 9, 2008
Perl on the fly
To replace string in a file on the fly using perl simply enter in the command line the following:
Friday, April 4, 2008
renaming files using perl
This is an example of how to rename a set of files that match a particular pattern.
#!/usr/bin/perl
use File::Find;
use File::Path;
die "usage:$0 (DIR)\n" unless @ARGV;
$dir = $ARGV[0];
finddepth(\&edits, $dir);
exit(0);
sub edits {
$fname = $_;
if (-f) {
if ($fname =~/[^\s].\.(cnf|dnf|eps|etat|planches)$/) {
print "Scanning $fname\n";
#$newname = $fname;
#$newname=~s/(.\./test_$1/;
my @values = split(/\./, $fname);
#foreach my $val (@values) {
#print "$val\n";
#}
my $pref=@values[0];
my $suff=@values[1];
$newname="test_" . $pref . "." .$suff;
print "$newname\n";
rename ($fname, $newname)
}
}
}
#!/usr/bin/perl
use File::Find;
use File::Path;
die "usage:$0 (DIR)\n" unless @ARGV;
$dir = $ARGV[0];
finddepth(\&edits, $dir);
exit(0);
sub edits {
$fname = $_;
if (-f) {
if ($fname =~/[^\s].\.(cnf|dnf|eps|etat|planches)$/) {
print "Scanning $fname\n";
#$newname = $fname;
#$newname=~s/(.\./test_$1/;
my @values = split(/\./, $fname);
#foreach my $val (@values) {
#print "$val\n";
#}
my $pref=@values[0];
my $suff=@values[1];
$newname="test_" . $pref . "." .$suff;
print "$newname\n";
rename ($fname, $newname)
}
}
}
File line ending from DOS to UNIX or MAC
Alt+x set-buffer-file-coding-system
Short cut : CTRL X ret F
Short cut : CTRL X ret F
Wednesday, March 26, 2008
Remove leading and trailing whitespace
To remove leading and trailing whitespace(or any trailing char):
- Regular Expression :
- s/^\s+//;
- s/\s+$//;
- Perl :
- Chomp();
- Python:
- strip();
Monday, March 24, 2008
How to read and write text file in python
list1=file("filename.txt").readlines() #don't forget the parenthesis
set1=set(liste1) #cast it to a set
set1=[elem.strip() for elem in set1] #strip all the elements of the set by removing trailing characters such us /t or /n
To find the differences with another set :
set3=set1.difference(set2)
To save into a file
fLog=tFile.open('filename.log','w')
First I add line return to each elem of the set
set4=[elem+"\n" for elem in set3]
Then I write the whole set into the file:
fLog.writelines(set4)
fLog.close()
set1=set(liste1) #cast it to a set
set1=[elem.strip() for elem in set1] #strip all the elements of the set by removing trailing characters such us /t or /n
To find the differences with another set :
set3=set1.difference(set2)
To save into a file
fLog=tFile.open('filename.log','w')
First I add line return to each elem of the set
set4=[elem+"\n" for elem in set3]
Then I write the whole set into the file:
fLog.writelines(set4)
fLog.close()
Sunday, March 23, 2008
Subscribe to:
Posts (Atom)