unixsolaris-10

convert multiple lines into single line in a file only after a specific pattern


I am trying to convert multiple lines into single line only after a specific pattern, in a text file on Solaris 10 machine.

file be like:-

<open>
   <bas>ABC1</bas>
   <stat>1</stat>
</open>
<open>
   <bas>ABC10</bas>
   <stat>1</stat>
</open>
<open>
   <bas>ABC11</bas>
   <stat>4</stat>
   <line>1234</line>
</open>
<new>
</new>

expected output:-

<open><bas>ABC1</bas><stat>1</stat></open>
<open><bas>ABC10</bas><stat>1</stat></open>
<open><bas>ABC11</bas><stat>4</stat><line>1234</line></open>
<new>
</new>

I tried with but didn't succeed

perl -pne 'chomp unless(/^<\/open>/);' file_name

Solution

  • Assuming the file original.txt contains:

    <open>
    <bas>ABC1</bas>
    <stat>1</stat>
    </open>
    <open>
    <bas>ABC10</bas>
    <stat>1</stat>
    </open>
    <open>
    <bas>ABC11</bas>
    <stat>4</stat>
    <line>1234</line>
    </open>
    <new>
    </new>
    

    And so.bash contains:

    #!/bin/bash
    
    awk -f so.awk original.txt
    

    and file so.awk contains:

    BEGIN {
        inopen=0
    }
    /<open>/ {
        inopen=1
        printf "%s",$0
        next
    }
    /<\/open>/ {
        inopen=0
        print
        next
    }
    inopen==1 {
        gsub(" ", "")
        printf "%s",$0
        next
    }
    { print }
    

    The output will be:

    <open><bas>ABC1</bas><stat>1</stat></open>
    <open><bas>ABC10</bas><stat>1</stat></open>
    <open><bas>ABC11</bas><stat>4</stat><line>1234</line></open>
    <new>
    </new>