Mistu4u
Mistu4u

Reputation: 5416

How to convert following text in required format in unix?

I have a file which has the following format:

1
2
3
4
5
6

I am trying to make it like:

1 2
3 4
5 6

I have tried

awk 'BEGIN { ORS= " "} {print}' test.txt

It makes 1 2 3 4 5 6. But I need to make it in the aforementioned format. I also tried

awk 'BEGIN { ORS= " "} {print}' test.txt | tr '  ' '\n'

but it seems tr does not consider double whitespaces and the result comes:

1
2
3
4
5
6

What can I do?

PS In the file there is one newline between 1 and 2 and 4 and 5 and so on and two newlines between 2 and 3 and 4 and 5 and so on. Due to limited knowledge in this editor I am not able to print that way.

Upvotes: 0

Views: 71

Answers (6)

Ell
Ell

Reputation: 947

There are many ways of accomplishing this task in unix. Aside from the answers already provided, here are several methods:

Using sed:

sed 'N;s/\n/ /' test.txt

Using awk:

awk 'ORS=NR%2?FS:RS' test.txt

Using paste:

paste -s -d" \n" test.txt

EDIT - I've just seen your note about the new lines. None of the above solutions in my answer will work correctly if there are multiple blank new lines in the file. You would first have to remove them using something like the below:

grep . test.txt | {solution from above}

Upvotes: 0

Mark Setchell
Mark Setchell

Reputation: 207425

If your file is called test.txt, you can do

xargs -L 2 < test.txt

Upvotes: 3

josifoski
josifoski

Reputation: 1726

Deleting first all empty lines, then using N option in GNU sed

sed '/^\s*$/d' file | sed 'N; s/\n/ /'

Upvotes: 0

twalberg
twalberg

Reputation: 62369

You can also use pr for this:

$ seq 10 | pr -t -T -a -s" " -2
1 2
3 4
5 6
7 8
9 10

Upvotes: 0

shellter
shellter

Reputation: 37258

Or as you posted an awk question, here it is in awk

 awk '{printf("%s %s", $0, (NR%2) ? "": "\n") }' file

output

1 2
3 4
5 6

IHTH

Upvotes: 0

Jason Hu
Jason Hu

Reputation: 6333

if you don't mind to use bash, i have an idea in mind:

content=`cat your_file`

while [ -n "$content" ]; do
    read a b content <<< $content
    echo $a $b >> target_file
done

this code can fold a string by two. notice that quote matters in this snippet.

Upvotes: 0

Related Questions