[Za-pm] Writing a search replace script
Nico Coetzee
ncoetzee1 at fnb.co.za
Wed Feb 25 22:12:01 CST 2004
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
For thos ineterested, you can use the following as a learning exercise:
1 #!/usr/bin/perl
2
3 use strict;
4 use File::Copy;
5
6 my $file = "/tmp/temp.conf"; # the config file to parse
7 my $username;
8
9 if( -e $file ) {
10
11 # First, get a valid username
12 my $valid = 0;
13 while( $valid < 1 ) {
14
15 print "Enter the username: ";
16 $username = <STDIN>;
17 print "\n";
18 chomp( $username );
19
20 # validate input
21 if( $username =~ /^\w{5,}/ ) { $valid++; }
22
23 print "Incorrect format for username - please enter it again.\n\n";
24
25 }
26
27 # Search and replace in files
28 open( INF, "< $file" ) or die( "Cant open $file for reading\n" );
29 open( OUTF, "> /tmp/balsa.tmp" ) or die( "Cant open $file for
writing\n" );
30
31 while( <INF> ) {
32
33 s/USERNAME/$username/eg;
34 print OUTF $_;
35
36 }
37
38 close( OUTF );
39 close( INF );
40
41 # move and overwrite the original file with the temp file
42 # but first make a backup copy:
43 my $bakfile= $file . ".bak";
44 rename( $file, $bakfile );
45 move( "/tmp/balsa.tmp", $file );
46 if( -e $file ) {
47
48 print "Operation succesful\n";
49
50 } else {
51
52 print "Operation failed\n";
53
54 }
55
56 } else {
57
58 # file does not exists
59 print "Sorry, the file $file does not exists on this system.\n";
60
61 }
62
63 exit;
64
65 1;
I included a lot of error checking to demonstrate a couple of nice features.
The 'move' command is NOT native to Perl, hence the 'use File::Copy'.
Cheers
Nico
> On Tuesday 24 February 2004 16:24, Karl Fischer wrote:
> I'm trying to write a script to automate balsa config files
> I all ready created a default file for the script to use I want to
> replace the USERNAME value with $username value I enter from the command
> line.
>
> any suggestions?
>
> Karl
>
>
> #!/bin/bash
> echo "Enter a valid Unix Username :"
> read $username
> #USERNAME is unix name of the person
> perl -pi -w -e 's|USERNAME|$username|g;' .gnome2/balsa
>
>
> _______________________________________________
> Za-pm mailing list
> Za-pm at mail.pm.org
> http://mail.pm.org/mailman/listinfo/za-pm
- --
BOFH excuse :
ether leak
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)
iD8DBQFAPXIRlXERkPl0klQRAoRrAJ9+LT43EUlEvZZESF+Nwke7O81DnQCdEw2h
ioduR7GoOyOu/nMb7Ocl5To=
=2KAM
-----END PGP SIGNATURE-----
-------------- next part --------------
A non-text attachment was scrubbed...
Name: filerename.pl
Type: text/x-perl
Size: 1118 bytes
Desc: not available
Url : http://mail.pm.org/pipermail/za-pm/attachments/20040226/dab04b58/filerename.bin
More information about the Za-pm
mailing list