Search code examples
bashawkappendpattern-matchingreadfile

Read lines from a file enclosed matching pattern of starting line and ending line and append it to another text file in bash


I have to read specific lines form a input file received in command line and alter all the lines and append it into another text file.

The input file has these lines(this set of lines apears only once):

00 TOOL     | Value of SIMIN:
00 TOOL     |   /absolute/path/to/some/required/file_1
00 TOOL     |   /absolute/path/to/some/required/file_2
00 TOOL     |   /absolute/path/to/some/required/file_3
00 TOOL     |   
00 TOOL     | Value of SIMOUT:

Lines we need to read are in-between two specific patterned.

Starting pattern:

00 TOOL     | Value of SIMIN: 

Ending pattern:

00 TOOL     |   
00 TOOL     | Value of SIMOUT:

Later I need to convert it to following lines and append it to another file:

export SIMIN=/absolute/path/to/some/required/file_1:$SIMIN
export SIMIN=/absolute/path/to/some/required/file_2:$SIMIN
export SIMIN=/absolute/path/to/some/required/file_3:$SIMIN

Got to know from this post how to read a file line by line.

But in my requirement, I may need to read the file in a buffer at a time, search for the above said line patterns and pick up the middle lines and alter them.

Any help/suggestion will be highly appreciated!


Solution

  • Could you please try following.

    awk '
    /SIMOUT/{
      flag=""
    }
    /SIMIN/{
      flag=1
    }
    flag && match($0,/\/[^ ]*/){
      print "export SIMIN=" substr($0,RSTART,RLENGTH)":$SIMIN"
    }
    '  Input_file
    

    In case you want to take its output into a output file append > output_file to above code.

    EDIT: Adding solution from ED sir too here.

    awk '/SIMOUT/{f=0} f&&/\//{printf "export SIMIN=%s\n", $NF} /SIMIN/{f=1}' Input_file