1838105 Members
3744 Online
110124 Solutions
New Discussion

join two line is a file

 
SOLVED
Go to solution
Ratzie
Super Advisor

join two line is a file

I have a file that is in dos format, which is ok, since I want to search on characters and the ^M and join it will the following line.

How it stands is I have a block of data 2 rows then a space, the first row ends with 5 digits and a ^M, I need to search for this and join it with the second line.

I want this...
2004/01/02 12:18:23 Access granted 05007
DO007 M-Turnstile (Left) 4D:60065 XXXXXX, ROBERT


With this...
2004/01/02 12:18:23 Access granted 05007 DO007 M-Turnstile (Left) 4D:60065 XXXXXX, ROBERT

How would I do that?
4 REPLIES 4
Ratzie
Super Advisor

Re: join two line is a file

I need to mention that this file has quite a few entries so the file would like...

/01/02 12:18:23 Access granted 05007
DO007 M-Turnstile (Left) 4D:60065 XXXXXX, ROBERT

/01/02 12:18:23 Access granted 05007
DO007 M-Turnstile (Left) 4D:60065 XXXXXX, ROBERT


/01/02 12:18:23 Access granted 05007
DO007 M-Turnstile (Left) 4D:60065 XXXXXX, ROBERT


I just copied paste but the data would be different in each group
Hein van den Heuvel
Honored Contributor
Solution

Re: join two line is a file


One of many solutions:

perl -p -e 'if (/\s\d{5}.$/) { chop; chop; $_ .= " ". <> }' < x

This looks explicitly for white-space, 5 decimals, random-character, end-of-line.

You could not chop but 'catch' the begin

perl -p -e 'if (/(^.*\s\d{5}).$/) { $_ = $1." ". <> }' < x

Or in awk:

awk '/ [0-9]+.$/{x=substr($0,1,length - 1); getline; print x,$0}' < x


Enjoy,
Hein.
H.Merijn Brand (procura
Honored Contributor

Re: join two line is a file

Some remarks about Hein's solutions:

> perl -p -e 'if (/\s\d{5}.$/) { chop; chop; $_ .= " ". <> }' < x

perl -pe 'if (/\s\d{5}.$/) {chop;chop}' < x

does the same, as does

perl -pe's/(\s\d{5})..\z)/$1/s'
but sorter and faster

because -p is nothing but an internal wrapper for

while (<>) {
... your -e code here ...
} continue { print }

so in hein's example he does not have to catenate the current line withh the next line, because both are printed anyway

> You could not chop but 'catch' the begin
>
> perl -p -e 'if (/(^.*\s\d{5}).$/) { $_ = $1." ". <> }' < x

perl -pe'/(^.*\s\d{5}).$/ and $_="$1 "' < x

in the same line of thought

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Ratzie
Super Advisor

Re: join two line is a file

Thanks