Transpose into single record

Hi Guys,

I have a file like below format

/my_dir/logs 2018-08-02 15:19:54 accepted connection from 10.140.75.239
/my_dir/logs 2018-08-02 15:19:56 authentication failed for id '123': Authentication failure
/my_dir/logs 2018-08-02 15:19:56 accepted connection from 10.140.75.239
/my_dir/logs 2018-08-02 15:19:59 authentication failed for id '123': Authentication failure
/my_dir/logs 2018-08-02 15:20:58 accepted connection from 10.140.75.239
/my_dir/logs 2018-08-02 15:21:00 authentication failed for id '123': Authentication failure

I would need to transpose it to single line using Awk

id,login_status,ip,time
123,Failed,10.140.75.239,2018-08-02 15:19:56 
123,Failed,10.140.75.239,2018-08-02 15:19:59
123,Failed,10.140.75.239,2018-08-02 15:21:00

Hello rohit_shinez,

In unix.com we encourage all users to do add their efforts which they have put to solve their own problem so kindly do add the same and let us know then.

Thanks,
R. Singh

Yes, and we also encourage people not to get hung up on using a single tool:

This is any easy task in PHP , OBTW.

But next time, as Ravinder mentioned, please at least TRY and post your own work FIRST before asking a question:

<?php
$file = file("/tmp/a.txt");
$line1 = $line2 = array();
$code = $ip = '';
echo "id,login_status,ip,time\n";
foreach ($file as $line) {
    $done = false;
    if (strpos($line, 'accepted') !== false) {
        $line1 = explode(' ', $line);
        $ip = str_replace("\n", "", $line1[6]);
    } elseif (strpos($line, 'failed') !== false) {
        $line2 = explode(' ', $line);
        $buf = str_replace("'", "", $line2[7]);
        $code = str_replace(":", "", $buf);
        $done = true;
    }
    if ($done) {
        $out = "$code,Failed,$ip,$line2[1] $line2[2]\n";
        echo $out;
    }
}
macos# php rohit_shinez.php
id,login_status,ip,time
123,Failed,10.140.75.239,2018-08-02 15:19:56
123,Failed,10.140.75.239,2018-08-02 15:19:59
123,Failed,10.140.75.239,2018-08-02 15:21:00

It's also an easy task in python as well, but I'll leave that up to you. Note: I don't process text files with awk , so I cannot help you there :slight_smile: sorry. However, what I can say is that this post is the "last straw" and as of today, our forum rules are forever changed:

***************************************************************

Show your own work first, before asking a question! Do not go to the Internet asking people to write all your code for you!!

If you want a solution, in awk, post what you have attempted yourself in awk FIRST. Show YOUR own work..

Please note:

As mentioned, this post was "the final event" of people asking others to write all their code for them; and so I have finally made a long promised rule change, effective today:

Effective Today: New Rule #3 of Forum Rules / Community Guidelines

1 Like