monkey- has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I am trying to find the best way to edit a bunch of files. The file is made of commets (with #, these are to be ignored) then single lines of infomation. There are 6 lines with:

"Key N 0x................"

Each . in the above is a alpha-numeric digit. I have to search for each line that starts with Key N (N being 0-5), count 14 places after 0x, then strip whats found afterwards then add a ;. This is way of my limits of perl. I am hoping someone might be able to help me out.

Thanks!

Replies are listed 'Best First'.
Re: manipulating file contents
by graff (Chancellor) on Sep 28, 2005 at 23:07 UTC
    I get the impression that you haven't tried looking at tutorials about regular expressions yet. You should do that -- it's not so complicated really. There's "perldoc perlretut" on your command line, and numerous tutorials that can be found on the web (including in our own Tutorials area).

    So look things up to see why something like this ought to do what you want:

    while (<>) { next if (/^#/); s/(Key [0-5] 0x\w{14}).*/$1/; } continue { print }
Re: manipulating file contents
by lidden (Curate) on Sep 29, 2005 at 00:07 UTC
    Here are two examples that does the same thing. I think the second one is easier to understand for someone new to Perl.
    while(<>){ print "$1;\n" if /^(Key [0-5] 0x[\da-f]{14})/i; } while( my $line = <>){ if( my ($match) = $line =~ /^(Key [0-5] 0x[\da-f]{14})/i ){ print "$match;\n"; } }
    or maybe you want a one-liner:
    perl -ni -le 'print "$1;" if /^(Key [0-5] 0x[\da-f]{14})/i' file.txt
    This will change "file.txt".
Re: manipulating file contents
by Skeeve (Parson) on Sep 28, 2005 at 23:02 UTC
    Have you even tried? Why don't you show us first before we solve this "basic task"?

    You might want to take a look at regular expressions (perldoc perlrequick or perldoc perlretut)

    $\=~s;s*.*;q^|D9JYJ^^qq^\//\\\///^;ex;print
      Yes I have been trying. Been trying to use grep and sed. Basically I can do this: cat file.txt | grep 'Key.[:alnum:].0x[:alnum:]*' | cut -c 22-

      So I was not shooting first with out reading. Sorry if it was "beneth" you to have asked for help on something that maybe "simple" to you.
Re: manipulating file contents
by GrandFather (Saint) on Sep 28, 2005 at 23:13 UTC

    You should show at least a sample of data that looks like your real data and a sample of the output you expect to generate. You should also show a small amount of code that you have written that attempts to do what you require - even if there is a line like # pull out the data I want here. How? in it.


    Perl is Huffman encoded by design.