Connecting Tech Pros Worldwide Help | Site Map

Replacing text after last | delimiter

Newbie
 
Join Date: Aug 2007
Posts: 9
#1: Aug 13 '07
hi,

i have a question about replacing text after a defined string.
for example :

the text goes.

##|######|#######_##| ########...
##|######|#######_##|########...
...

i'm trying to replace the text after the last '|' simbol with the expresion:

s/$'/$a/;

but it doesn't work in fact the :

s/$` /$a/

works but only when there is space between the | and next word.
also if i try to do this : s/$`/$a/ it replaces my expression with the $a .like this:
$a|########...

if i wasn't clear enough my goal is to have this in the end:

##|######|#######_##|$a


thank you!
numberwhun's Avatar
Site Moderator
 
Join Date: May 2007
Location: New Hampshire
Posts: 2,566
#2: Aug 13 '07

re: Replacing text after last | delimiter


Well, my question to you would be, are there always going to be 4 fields, separated by a "|"? If there are, then you could do the following:

Expand|Select|Wrap|Line Numbers
  1. use strict;
  2. use warnings;
  3.  
  4. open(FILE, "<Text1.txt");
  5.  
  6. while(<FILE>)
  7. {
  8.     chomp($_);
  9.     my @line = split(/\|/, $_);
  10.  
  11.     $line[3] = $a;
  12. }
  13.  
If not, then you can use the "$#line" syntax to determine the last array index and then set it from there.

Regards,

Jeff
Newbie
 
Join Date: Aug 2007
Posts: 9
#3: Aug 13 '07

re: Replacing text after last | delimiter


well, it will always be 4 fields at least, but there could be even few 100 or even 1000 fields with quite a lot of data in one field. but i need only first 3 and the rest i want to replace with a defined variable.

those are txt files and quite large from 2 GB up.

i was considering to transform it to array but i think that would drastically slow down the process (or not?).

thanks,

robert
numberwhun's Avatar
Site Moderator
 
Join Date: May 2007
Location: New Hampshire
Posts: 2,566
#4: Aug 13 '07

re: Replacing text after last | delimiter


I am going to assume that you mean that there could be 100's or even 1000's of "lines" in the file, not fields.

That should not be a problem. The code above will take and process each line individually. All you would need to do after reading each line, is have it outputted to a new file if that is what you wanted to do.

Regards,

Jeff
Reply


Similar Perl bytes