ABX
ABX

Reputation: 113

Extract specific line of code using awk (or non-awk) from a log file

I am trying to find a way to extract scripts from the log file generated.

I am stuck at a place where a command calls for multiple files and the script separates them with a trailing "\" for line continuity. For example, a sample script is:

my_command -option \
file1 \
file2 \
file3
my_command2 .. ..

It looked easy but somehow the trick is not hitting me at this point. Please help. Every line in the log starts with a specific identifier for command, like:

:: Script_Command:: my_command -option \
:: file1 \
:: file2 \
:: file3 
:: Info lines....
:: More info lines ...
:: Script_Command:: my_command2 ... ..
:: Info lines ...

So I used:

awk '/Script_Command/ {print }'

And then I tried to combine it with a if condition with:

awk '/Script_Command/ {print substr(length(),1)}'

But the entire thing is not falling in place. Please help.

Edit: The closest I got is here:

awk '{if ($NF=="\\" ||  == "Script_Command::") print ;}' file

It still leaves the file3 line as it does not match anything.

Pure intention is: 1. When Script_Command is matched, print line. 2. When "\" is matched, print the next line. 3. When both are matched, print line and next line.

Upvotes: 1

Views: 651

Answers (3)

ABX
ABX

Reputation: 113

I finally got this working with following command:

awk '/\\/ && /Script_Command/ {print $0;getline;print $0;next} /Script_Command/ {print $0;next} /\\/ {getline;print $0}'

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47137

If each continues line starts with :: one can use awk like this:

awk '!/^::/ { p = 0 }           # Set p = 0 if line does not start with ::
      /Script_Command/{ p = 1 } # Set p = 1 when line contains Script_Command
      p'                        # Print if p is truly

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47137

You can use sed for this:

sed -n '/Script_Command/ {:a;/\\$/!be;N;ba;:e;p;}'

Breakdown

                           # -n disables auto printing.
sed -n '/Script_Command/ { # Match regex
  :a                       # Define label 'a'
  /\\$/!be                 # Goto 'e' unless pattern space ends with \
  N                        # Append next line to pattern space
  ba                       # Goto 'a'
  :e                       # Define label 'e'
  p                        # Print pattern space
}'

You can add [[:space:]]* to /\\$!be if you want to read lines ending in slash followed zero or more spaces:

/\\[[:space:]]*$/!be

Upvotes: 1

Related Questions