Solved

[Q] Search/replace within text file

Posted on 1997-10-13
7
187 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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
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…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

708 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

11 Experts available now in Live!

Get 1:1 Help Now