Code_rocks Code_rocks - 3 months ago 8
Bash Question

Merge all line starting with IF and ending with semicolon in shell script

i am stuck in below problem. I have done this with while loop and it is working fine but not able to omit the sequence number appended with string in each loop.


i have a file content


1 SELECT abc from a ;

2 .IF activi <> 1
3 THEN
4 QUIT;
5 .IF ERROR <> 0 THEN QUIT ERROR;
6 SELECT
7 a,
8 b,
9 c
10 FROM xyz;
11 .IF ERROR <> 0
12 THEN
13 QUIT ERROR;



i want to edit in same file
with the following output


1 SELECT abc from a;
2 .IF activi <> 1 THEN QUIT ;
5 .IF ERROR <> 0 THEN QUIT ERROR;
6 SELECT
7 a,
8 b,
9 c
10 FROM xyz;
11 .IF ERROR <> 0 THEN QUIT ERROR;

Answer

With sed:

$ sed '/\.IF/{:a;/; *$/!{N;s/ *\n *[0-9]*//;ta}}' file

Output:

1 SELECT abc from a ;

   2 .IF activi <> 1 THEN QUIT;
   5 .IF ERROR <> 0 THEN QUIT ERROR;
   6 SELECT 
   7 a,
   8 b,
   9 c
   10 FROM xyz;
   11 .IF ERROR <> 0 THEN QUIT ERROR;

Explanation:

sed '
/\.IF/ {                   # for lines containing ".IF"
    :a;                    # define a "a" label for upcoming loop
    /; *$/! {              # if line does not contain ";"
        N;                 # add next line to pattern space
        s/ *\n *[0-9]*//;  # remove newline and leading digits
        ta;                # loops to label "a" if ";" is not found
    }
}' file