MrD
MrD

Reputation: 43

Joining a pair of lines with specific starting points

I know that with sed I can print

cat current.txt | sed 'N;s/\n/,/'  > new.txt
A
B
C
D
E
F

to

A,B
C,D
E,F

What I would like to do is following:

A
B
C
D
E
F

to

A,D
B,E
C,F

I'd like to join 1 with 4, 2 with 5, 3 with 6 and so on. Is this possible with sed? Any idea how it could be achieved?

Thank you.

Upvotes: 4

Views: 74

Answers (3)

Jotne
Jotne

Reputation: 41456

An awk version

awk '{a[NR]=$0} NR>3 {print a[NR-3]","$0}' current.txt
A,D
B,E
C,F

This solution is easy to adjust if you like other interval.
Just change NR>3 and NR-3 to desired number.

Upvotes: 0

Scrutinizer
Scrutinizer

Reputation: 9926

Try printing in columns:

pr -s, -t -2 current.txt

Upvotes: 7

Lev Levitsky
Lev Levitsky

Reputation: 65791

This is longer than I was hoping, but:

$ lc=$(( $(wc -l current.txt | sed 's/ .*//') / 2 ))
$ paste <(head -"$lc" current.txt) <(tail -"$lc" current.txt) | column -t -o,

The variable lc stores the number of lines in current.txt divided by two. Then head and tail are used to print lc first and lc last lines, respectively (i.e. the first and second half of the file); then paste is used to put the two together and column changes tabs to commas.

Upvotes: 0

Related Questions