TransWikia.com

print lines as columns two by two

Unix & Linux Asked by Djabri Josef on January 24, 2021

i have this kind of file and i’m searching a way to take just the last 2 columns and print them as one line two by two , can someone give me an idea ! thanks
input:

  1     0.00     435.9     6.04
  2     6.04     691.7    27.61
  3    33.65     964.5    10.03
  4    43.68    1932.5

output

435.9 6.04     691.7 27.61     964.5 10.03    1932.5

3 Answers

somethis like this?

awk '{printf ("%s %st", $3, $4)}' file

or maybe like this to handle the missing fields

awk '{field3=$3; field4=$4} $3==""{field3="t"} $4==""{field4="t"} {printf ("%s %st", field3, field4)}' file

Correct answer by capt_zipoc on January 24, 2021

Using an awk-paste pipeline we print the third and fourth fields, separated by a single space, and then they all get thrown onto a single line by paste's -s option, with each pair separated by the paste's default delimiter TAB=t.

$ awk '{print $3, $4}' file | paste -s -

If we want to stay within awk, that is also possible:

$ awk '
    BEGIN { s[1] = "t"; ORS = "" }
    { print s[(NR>1)] $3, $4 }
    END { print RS }
' file

We can also do a cut-paste job of it, but before that a small edit has to be done, viz., transmuting all whitespace to a space, squeeze multiple spaces, and strip leading space (if any). This is due to cut requiring a single char as delimiter and cut does not ignore leading delimiters.

$ < file sed -Ee 's/s+/ /g;s/^ //' |
    cut -d' ' -f3,4 | paste -s -

Answered by Rakesh Sharma on January 24, 2021

Python

#!/usr/bin/python
import re
m=re.compile(r's{1,}')
t=[]
k=open('file.txt','r')
for i in k:
    j=re.sub(m," ",i)
    try:
        o=j.strip().split(' ')
        if (len(o) == 4):
            y="{0} {1}".format(o[2],o[3])
        elif (len(o) == 3):
            y="{0}".format(o[2])
        else:
            print "Number of columns is less than 3"
        t.append(y)

    except:
        pass

print "t".join(t)

output

 python test.py 
435.9 6.04  691.7 27.61 964.5 10.03 1932.5
praveen@praveen:~

$

awk command

awk '{print $3,$4}' filename| perl -pne "s/n/t/g"

435.9 6.04 691.7 27.61 964.5 10.03 1932.5

Answered by Praveen Kumar BS on January 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP