Search code examples
awksedvim

How can I adjust a text file in VIM to have two columns instead of three while not splitting paired data?


Hello there and thank you for reading this!

I have a very large text file that looks something like this:

a1 b1 a2
b2 a3 b3
a4 b4 a5
b5 a6 b6 

I would like my text file to look like this:

a1 b1 
a2 b2 
a3 b3
a4 b4 
a5 b5 
a6 b6 

In reality, these values are paired lon/lat coordinates. If it is useful the values look like:

1.591336e+02 4.978998e+01 1.591162e+02
4.977995e+01 1.590988e+02 4.976991e+01
1.590815e+02 4.975988e+01 1.590641e+02
4.974984e+01 1.590468e+02 4.973980e+01

I have been learning in vim, but I do have access to other tools if this is easier done elsewhere. Should I be looking for a sed or awk command that will assess the amount of spaces in a given row? I appreciate any and all advice, and if I can offer any more information, I would be glad to!

I have searched for other folks who have had this question, but I don't know how to apply some of the solutions I've seen for similar problems to this - and I'm afraid of messing up this very large file. I am expecting the answer to be something using sed or awk, but I don't know how to be successful with these commands with what I've found so far. I'm rather new to coding and this site, so if I missed this question already being asked, I apologize!

All the best!

EDIT: I used

sed 's/\s/\n/2;P;D' file.txt > newfile.txt

to turn my file into:

a1 b1
a2^M 
b2 a3
b3^M
a4 b4
a5^M
b5 a6
b6^M

I then used:

dos2unix newfile.txt

to get rid of the ^M within the data. I haven't made it to the structure, but I am one step closer.


Solution

  • $ tr ' ' '\n' <input_file|paste -d" " - -
    a1 b1
    a2 b2
    a3 b3
    
    $ sed 's/ /\n/2; P; D' <(tr '\n' ' ' <input_file)
    a1 b1
    a2 b2
    a3 b3
    
    $ tr '\n' ' ' <input_file|xargs -d" " printf '%s %s\n'
    a1 b1
    a2 b2
    a3 b3