I have this two-entry table resulting from a program output:

Variable1  : Value1  
Variable2  : Value2  
Variable3  : Value3  
Variable4  : Value4  
Variable5  : Value5  
Variable6  : Value6  
Variable7  : Value7 

I need to extract both the first and the fifth pairr\s, something I do with grep:

$ {program command} | grep -e Variable1 -e Variable5

resulting in this output:

Variable1  : Value1  
Variable5  : Value5  

The problem here is that I need both pairs on the same line but the grep -e command prints a LF/CR after every -e; I need the four pairs in the same line to make a final sort based on file size. I think I could make this in awk or perl from the same command line but alas I'm still somewhat green with them.

Any ideas? Thanks in advance.


If you just want to join the lines use tr to delete the newline:

$ {program command} | grep -e Variable1 -e Variable5 | tr -d '\n'

To do the whole thing in awk:

$ {program command} | awk '/Variable[15]/ { printf("%s ", $0) }'

Same in sed:

$ {program command} | sed -n '/Variable[15]/H; $ { x; s/\n/ /g; p }'

If you just want join both lines from grep, the easiest way is to pipe through fmt.

$ {program command} | grep -e Variable1 -e Variable5 | fmt

If the lines are too long, use the -w LINELENGTH option of fmt.

  • I never used fmt before so thanks for the suggestion, I'll give it a try.
    – solr
    Jan 2 '18 at 14:10

You can remove the newline by Perl's substitution

perl -ne 's/\n/ /; print if /Variable[15]/'

If you need a newline at the end, add

perl -ne 's/\n/ /; print if /Variable[15]/ }{ print "\n"'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.