How to join each double lines?
I have a text file,
a1
a2
b1
b2
c1
c2
...
I want to join by two lines so one can sort
it:
a1:a2
b1:b2
c开发者_开发技巧1:c2
...
I'm using bash. the read
function will eat the leading space, which is undesired. And I hate to write simple stupid C programs.
Then, I can use tr : "\n"
to split the joined file back to two files.
paste -s -d ':\n' file
should do it.
For example:
% cat f
a1
a2
b1
b2
% paste -s -d ':\n' f
a1:a2
b1:b2
sed 'N;s/\n/:/;' < srcfile > destfile
Looking over there I found an example that can be converted into:
sed '$!N;s/\n/:/' < file
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
awk '{line=$0; printf line; if (getline) printf ":" $0; print ""}' inputfile
edit in-place with backup:
perl -i.bak -pe 's/\n\Z/:/ if $.%2' file
edit in-place no backup:
perl -i -pe 's/\n\Z/:/ if $.%2' file
Here is a 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 you case you can use the function like this:
njoin("/path/to/file", n=2, linesuffixe=":")
精彩评论