[Linux-disciples] help me write a shell script

Stephen R Laniel steve at laniels.org
Thu Jul 17 09:45:57 EDT 2008


On Thu, Jul 17, 2008 at 09:37:09AM -0400, Jamie Forrest wrote:
> 1) Search for instances of a word in a file and replace with another  
> word

a) sed(1) is your tool. This command
   will do the search-and-replace and
   dump the output to stdout:

   sed -e 's/old_str/new_str/g' filename

   Once you've examined the output from
   that command and made sure that it
   did the replacement properly, you can
   have sed make the edits in the file
   itself (rather than to stdout) like
   so:

   sed -i -e 's/old_str/new_str/g' filename

> 2) Merge three files into one (cat file1 file2 file3 > file4 ?)

b) Yes, that cat(1) call is what you want.

> 2) Search for all instances in file4 of funky special chars and  
> delete: Ôªø

c) Do you have a particular set of
   special characters you want to
   delete, or do you want to delete all
   funky special characters? If the
   former, then use sed(1). If the
   latter ... probably use Perl, but I'd
   have to think about it.

> 3) Search for all comments in the file, delimited by /* and */ and  
> delete

d) The trick here is that sed(1) works
   on single lines, whereas /* ... */
   can span multiple lines. I believe
   awk(1) can do multiline things, but
   here I'd just use Perl. Here's a
   quick-and-dirty way to do it, with
   disclaimers afterward:

   #!/usr/bin/perl
   use strict;
   use warnings;
   use File::Slurp;
   
   my $file_contents = read_file('/path/to/filename');
   $file_contents =~ s#/\*.*?\*/##g;
   print $file_contents;

   Disclaimers:

   i)   I've not tested this, but it
        should do what you want.
   ii)  It dumps the changed file to
        stdout. If you want to save it
        back to the original file, you
        can do something like

        myscript.pl filename > foo
        mv foo filename
   iii) $file_contents, in that script,
        will grow quite large if
        /path/to/filename is a large
        file. So if the file is large,
        this will eat up lots of memory.

-- 
Stephen R. Laniel
steve at laniels.org
Cell: +(617) 308-5571
http://laniels.org/
PGP key: http://laniels.org/slaniel.key


More information about the Linux-disciples mailing list