How to join each double line?

I have a text file,

a1
a2
b1
b2
c1
c2
...

I want to join two lines so that sortit:

a1:a2
b1:b2
c1:c2
...

I am using bash. the function readwill consume leading space, which is undesirable. And I hate writing plain stupid C programs.

Then I can use tr : "\n"to split the combined file into two files.

+3
source share
7 answers

paste -s -d ':\n' file must do it.

For instance:

% cat f
a1
a2
b1
b2
% paste -s -d ':\n' f
a1:a2
b1:b2
+12
source
sed 'N;s/\n/:/;' < srcfile > destfile
+3
source

, , :

sed '$!N;s/\n/:/' < file
0
INDEX=0
A=""
B=""

for i in `awk '{print $1}' input`
    do
    if [ $INDEX -eq 0 ]; then
        A=$i;
        let INDEX=1;
    fi

    if [ $INDEX -eq 1 ]; then
        B=$i;
        echo $A:$B
        let INDEX=0;
    fi
done
0
awk '{line=$0; printf line; if (getline) printf ":" $0; print ""}' inputfile
0

:

perl -i.bak -pe 's/\n\Z/:/ if $.%2' file

:

perl -i -pe 's/\n\Z/:/ if $.%2' file
0

Here is the solution in python:

#!/usr/bin/python3

def njoin(filename, outfn="", n=3, linesuffix=" "):
    if not outfn:
        outfn = filename + ".join"
    with open(filename) as infh, open(outfn, "w") as outfh:
        nline = 0
        for line in infh:
            if nline % n != n-1:
                line = line.rstrip() + linesuffix
            outfh.write(line)
            nline += 1

In this case, you can use the following function:

njoin("/path/to/file", n=2, linesuffixe=":")
0
source

Source: https://habr.com/ru/post/1774899/


All Articles