awk multiple lines

When your data is consistent it is easy to use awk with multiple lines like this. Can we please make this portable so I can use this in both RHEL and AIX?

awk '{RS="/directory1" } $7 ~ /drwxr-xr-x/ {print $1 " "  $7}' file

What do I do when the data is not consistent? When your data is not consistent like this it does not work.

server1 | CHANGED | rc=0 >>
drwxr-xr-x. 8 root root 77 Apr 18  2018 /directory1
server2 | CHANGED | rc=0 >>
drwxr-xr-x. 7 root root 120 Feb 14  2019 /directory2
server3| FAILED | rc=2 >>
ls: /director3: No such file or directorynon-zero return code
server5 | FAILED | rc=2 >>
ls: cannot access /sirectory3: No such file or directorynon-zero return code

There is another problem I have. Sometimes the data has more than two lines.

server4| UNREACHABLE! => {
    "changed": false,
    "msg": "Data could not be sent to remote host \"server4\". Make sure this host can be reached over ssh: ",
    "unreachable": true
}

You are using /directory1 as a record separator. That means awk just reads the text including \n characters which display. And not ignoring them using the default EOL operation - chop off the newline.

Try using gsub on each record to remove the newline character from $0 , replace that with a space.

Whenever you mess with either pagination or carriage control you can get "unexpected results" in standard tools.

I don't think you can have a swiss army knife solution to a wild card problem. Please decently describe the data conents / structure in all cases, for every case, in detail. Are above the only three cases, or are there more? Is that pipe symbol enclosed in spaces or not always? Could it be used as a field separator? WIll the more-than-four-line data always be using braces to enclose the last field? One level of braces only?

You seem to want to print sth. like

server1 drwxr-xr-x
server2 drwxr-xr-x

in the "good cases". What should be the output in the "FAILED" cases? What in the multiline case?

You could use sth. like this to get the full records to operate upon:

awk -F\| '
function RDREST()       {getline X; $0 = $0 " | " X
                        }
/{$/    {while (! /}/) RDREST()
        }
NF < 4  {RDREST()
        }
1
' file
server1 | CHANGED | rc=0 >> | drwxr-xr-x. 8 root root 77 Apr 18  2018 /directory1
server2 | CHANGED | rc=0 >> | drwxr-xr-x. 7 root root 120 Feb 14  2019 /directory2
server3 | FAILED | rc=2 >> | ls: /director3: No such file or directorynon-zero return code
server5 | FAILED | rc=2 >> | ls: cannot access /sirectory3: No such file or directorynon-zero return code
server4 | UNREACHABLE! => { |     "changed": false, |     "msg": "Data could not be sent to remote host \"server4\". Make sure this host can be reached over ssh: ", |     "unreachable": true | }
1 Like