UNIX awk : Print line with "CLICKS", if * on pos 7 skip line, if contain "\" concat next line, if next line has * concat 3rd line

Viewed 73

I need to print line from file which contains "CLICK" and are not commented (* on position 7) like line 000001,

if the line has CLICK and "\" then concatenate the next line too , if next line is commented then skip that line and concatenate the next one : like line number 000002 concat with line 000004 skipping line 000003.

if concatenated line (next) also contains '\' then we do not need to concat the 3rd line, by which i mean we do Delete the line from the output, like we deleted the lines 3 and 5 because they are not required the core logic as stated previously: [if the line has CLICK and "\" (both) then concatenate the next line, if line only has CLICK print that line only,everything other line is deleted from output ] .

so in this case example is: 000006 concats line 000007 but do not concats 000008 which means 000008 will be deleted from the output

INPUT FILE:

000001  HECTOR CLICK MOUSE
000002  ANNE CLICK MOUSE \
000003* AND PRESSES KEYBOARD
000004  AND PRESS KEYBOARD
000005* CLARK CLICK MOUSE
000006 MIKE CLICK MOUSE \
000007 AND PRESS KEYBOARD \
000008 AND TAPS SCREEN 

output

000001  HECTOR CLICK MOUSE
000002  ANNE CLICK MOUSE \ AND PRESS KEYBOARD
000006 MIKE CLICK MOUSE \ AND PRESS KEYBOARD \

I have created this :

awk '
/^...... +/{
if  ($0 ~ /CLICK/ && $0 ~ /\\/)
      {l1=$0;getline; print l1 $0}
else if 
    ($0 ~ /CLICK/ && $0 !~ /\\/)
     {print $0} ;
}' *> outfile

the outcome is quite close but there are two problems :

1. the data is written twice
2. commented second line is also printed, i tried /^...... +/ inside the if but it gave error
1 Answers
$ cat tst.awk
$1 ~ /\*$/ { next }
saved != "" {
    sub(/^[^[:space:]]*[[:space:]]+/," ")
    print saved $0
    saved = ""
}
/CLICK/ {
    if ( /\\$/ ) {
        saved = $0
    }
    else {
        print
    }
}

$ awk -f tst.awk file
000001  HECTOR CLICK MOUSE
000002  ANNE CLICK MOUSE \ AND PRESS KEYBOARD
000006 MIKE CLICK MOUSE \ AND PRESS KEYBOARD \

Skip every comment line. For every other line: When we find a line containing CLICK, if it ends in backslash then save it, otherwise print it. For every line, if we have a saved string then print it in front of the current line. The sub() is to change the leading number and spaces into a single blank char before printing the current line at the end of the saved line.

Related