Solved

[Q] Search/replace within text file

Posted on 1997-10-13
7
225 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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…
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
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…
Six Sigma Control Plans

696 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