Search code examples
perlextracttransfer

Extract a string from one line and put it in the precceding line (Perl)


I don't have much experience in programming with perl but have to solve a heavy problem.I have data in this format:

*IDENTIFIER A  
ABCDEFGHIJKLMNOPQRSTVUWXYZ  
3. line  
4. line  
*IDENTIFIER B  
ABCDEFGHIJKLMNOPQRSTVUWXYZ  
3. line  
4. line  
...  

I want to delete the first 5 symbols from the line under the identifier and add these to the identifier line. Each identifier starts with a *. The new file should look like:

*IDENTIFIER A:ABCDE  
FGHIJKLMNOPQRSTVUWXYZ  
3. line  
4. line  
*IDENTIFIER B:ABCDE  
FGHIJKLMNOPQRSTVUWXYZ  
3. line  
4. line  
...    

I would be very happy about every kind of help. THX


Solution

  • That's not so hard.

    while (<>) {
        if (/^\*/) {                                     # Identifier
            chomp;                                       # Remove the \n.
            my $nextline = <>;                           # Read the next line.
            my $first_5 = substr $nextline, 0, 5, q();   # Move the 1st 5 characters to a variable.
            print "$_:$first_5\n$nextline";              # Print the identifier, the 5 chars,
                                                         #     newline, nextline.
        } else {
            print
        }
    }