Solved

[Q] Search/replace within text file

Posted on 1997-10-13
7
195 Views
Last Modified: 2012-05-04
I am working on a script to open up a semi-database -- actually a text file set up like this:
    value 1a <TAB> value 2a <TAB> value 3a
    value 1b <TAB> value 2b <TAB> value 3b

Once a certain action is performed upon one of the database entries (i.e. value 1b, 2b, 3b), I would like to delete that line from the text file. The first value on each line is unique within the whole file, replication of that first value is not a concern in writing the function.

When I import each line into the script, I set it up as such:
        $fields[0]
        .
        .
        $fields[n]

So, if (based on my first example) I was done with the line containing values 1b, 2b and 3b, I would like the entire second row deleted or replaced by a series of empty spaces.
Any help would be immensely appreciated.

Thanks
Adam Grayson
0
Comment
Question by:Dyrewolf
  • 3
  • 3
7 Comments
 
LVL 51

Accepted Solution

by:
ahoffmann earned 100 total points
ID: 1207692
$match='1b';
open(FID,"<text_file");
while(<FID>) {
   if (grep( /^$match/, $_ )) { continue; }
   $count++;
   $db[$count]=$_;
}

This examples reads your file into array $db, ignoring lines beginning with $match.
0
 
LVL 84

Expert Comment

by:ozo
ID: 1207693
you should usually check your open statements to be sure they succeed.
grep is usually used on a list, not a scalar.
As written the regular expression needs to be recompiled for each line of <FID>.
In Perl, "continue" is usualy spelled "next".
$count++; $db[$count]=$_; might be written as push(@db,$_)
(except that you're skipping $db[0])
Maybe ahoffmann was thinking of
@db = grep !/^$match/,<FID>;
(but this will also ignore lines begining with 1bb <TAB>,
and you'd also want to be carefull about metacharacters in $match)
0
 
LVL 84

Expert Comment

by:ozo
ID: 1207694
(continue does have a meaning in Perl, but it's not the same as C's continue.)
it's main use is to define the for(;;){} loop rigorously.
for( $i=1; $i<10; $i++ ){ ... next; ... }
is the same as
$i=1; while( $i<10 ){ ... next; ... }continue{ $i++ }

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 51

Expert Comment

by:ahoffmann
ID: 1207695
ozo, I was lazy.
dyrewolf, here're the reasons:
  - the open check is in all **my** scripts :-))
  - grep or if or ??, the Camel book somewhere recomments grep
  - yes, the pattern should have the o flag
  - continue should be next
  - using arrays as in C or perl's push,
      perls's (Larry Wall's) slogan: There's More Than One Way To Do It.
  - 1bb: no, I didn't write a regex for all possible patterns (that was not the subject of this question)

ozo, I've seen that you are more used to perl than I. Lets talk
about such things  at  hoagascht@gmx.net, if you like.
0
 

Author Comment

by:Dyrewolf
ID: 1207696
Thanks a lot, both of you. To print the results back to the text file without the deleted line, can I just overwrite the whole file and print @db? If so, how?

Thanks
Adam
0
 
LVL 51

Expert Comment

by:ahoffmann
ID: 1207697
If you want to replace strings on the fly, you have to use perl's read() and write() function (they are direct interfaces to the corresponding system calls !).

But I recommend that you write the result to a new file and then move it to the original one:
  system("rm old_file");      # or unlink( old_file )
  system("mv new_file old_file");
0
 
LVL 84

Expert Comment

by:ozo
ID: 1207698
ahoffmann, where in the Camel book does it recommend grep on a scalar?
On "More Than One Way To Do It", Lary has an interesting sermon at
http://london.wall.org/larry/keynote/keynote.html
one of the points of which is that we shouldn't complain about people using Perl in a C or other style.
(Even if I was merely pointing out "another way to do it",
which I think is appropriate if this forum is meant to help people learn Perl)
On 1bb, the point was that the regexp does match more patterns than the given value.

Since this question is now a PAQ that costs points to visit, I'd
rather not continue the discussion here, you could start a new 0 point question,
or ask contact@experts-exchange.com to forward a message.

Dyrewolf, one way to write out @db might be:

open(F,">new_text_file") || die "can't write file $!";
print F @db;
close F;
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many time we need to work with multiple files all together. If its windows system then we can use some GUI based editor to accomplish our task. But what if you are on putty or have only CLI(Command Line Interface) as an option to  edit your files. I…
Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

27 Experts available now in Live!

Get 1:1 Help Now