You're viewing a comment by Stuart Marmorstein and its responses.

Stuart Marmorstein Permalink
February 26, 2013, 19:28

I use some tilde-delimited .txt and .ini files as searchable databases. Running Win 7 32-bit. Perl may work faster than some routines I am currently using. If I want to work with a record in a file that looks like this:

ADVJSMF=Last~Familiar Name~First Name~Salutation~Street Address~City~State~zipcode~email address~work number~home number~etc. and I wanted to use a one-liner to retrieve info only in one field or manipulate only one field (for instance the email field) based on the identifier to the left of the equal sign, is there a way to do that? If so, I'd love to know how to do that.

In a similar database containing records, I also perform searches to find out whether someone has a birthday that falls within a few days of the search date I am using, but I could save that question for another time. Many thanks! Stuart

Comment Responses

March 26, 2013, 16:45

Hi Stuart!

It's definitely possible to do that. Here's the basic idea. First you'd split the line into left and right, and then split the right part into fields:

perl -nle "
 my ($left, $right) = split '=', $_, 2;
 my @fields = split '~', $right;
"

Now you just have to test if $left is something that you're looking for, for example, if it is "ADVJSMF":

perl -nle "
 my ($left, $right) = split '=', $_, 2;
 my @fields = split '~', $right;
 if ($left eq 'ADVJSMF') {
   # do something
 }
"

Now just replace # do something with the actual thing to do. For example, to print First Name, you'd print $fields[2]:

perl -nle "
 my ($left, $right) = split '=', $_, 2;
 my @fields = split '~', $right;
 if ($left eq 'ADVJSMF') {
   print $fields[2];
 }
"

Modifying fields is a bit trickier as it involves re-assembling the fields, left part and right part.

But here's how you'd do it:

perl -nle "
 my ($left, $right) = split '=', $_, 2;
 my @fields = split '~', $right;
 if ($left eq 'ADVJSMF') {
   $fields[2] = 'New First Name';
 }
 my $new_fields = join '~', @fields;
 print $left, '=', $new_fields;
"

This modifies the First Name, and then prints the updated line.

Reply To This Comment

(why do I need your e-mail?)

(Your twitter handle, if you have one.)

Type the word "cdrom_303": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.