Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two lines in one

I have a problem with select of specify lines and join every second lines in one line.

i.e. I have two file:

cat lol1.txt
2015-11-15 12:44:34
Name    Value1  Value2
lol1    3   2
lol2    2   5
2015-11-15 12:44:44
Name    Value   Value2
lol1    7   1
lol2    5   1
2015-11-15 12:44:54
Name    Value   Value2
lol1    3   9
lol2    9   2

and

cat lol2.txt
2015-11-16 10:23:31
Name    Value   Value2
lol1    3   4   
lol2    4   7
2015-11-16 10:23:41
Name    Value   Value2
lol1    7   5
lol2    9   2
2015-11-16 10:23:51
Name    Value   Value2
lol1    2   4   
lol2    2   5

And command:

cat lol.txt lol2.txt | grep 'lol1\|2015'

returns:

2015-11-15 12:44:34
lol1    3   2
2015-11-15 12:44:44
lol1    7   1
2015-11-15 12:44:54
lol1    3   9
2015-11-16 10:23:31
lol1    3   4   
2015-11-16 10:23:41
lol1    7   5
2015-11-16 10:23:51
lol1    2   4   

Now I have to join every second lines in one. I mean:

2015-11-15 12:44:34 lol1    3   2
2015-11-15 12:44:44 lol1    7   1
2015-11-15 12:44:54 lol1    3   9
2015-11-16 10:23:31 lol1    3   4
2015-11-16 10:23:41 lol1    7   5
2015-11-16 10:23:51 lol1    2   4   

And another question. How to choose line with date and time with use something else than grep 2015, because in next year date will start from 2016 and i will have to change script.

Thanks.

like image 219
Damian Silkowski Avatar asked Dec 01 '25 06:12

Damian Silkowski


2 Answers

You can pipe that to the following awk command:

... | awk 'NR%2{last=$0;next}{print last, $0}'

It stores the whole line into the variable last on odd lines and prints last plus the current line on even lines.

Or shorter:

... | awk '!(NR%2){print l, $0}{l=$0}'
like image 161
hek2mgl Avatar answered Dec 02 '25 21:12

hek2mgl


awk to the rescue! You don't need cat/grep.

 $ awk '/^[0-9-]{10}/{printf $0 FS} /lol1/' lol1.txt
2015-11-15 12:44:34 lol1    3   2
2015-11-15 12:44:44 lol1    7   1
2015-11-15 12:44:54 lol1    3   9

you can extend the file list. The first pattern is a simplistic date content pattern; based on your data should be enough, if not easy to convert to a better one.

like image 34
karakfa Avatar answered Dec 02 '25 21:12

karakfa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!