2

I need to concatenate a text file with a couple of lines. This one is my situation:

USER abc  
PASS 123  
USER efg  
PASS 456   
USER hil  
PASS 789

and so on...

I need an output like this:

USER abc PASS 123  
USER efg PASS 456     
USER hil PASS 789

I tried solutions like:

awk 'NR % 2 == 1 { o=$0 ; next } { print o "<sep>" $0 } END { if ( NR % 2 == 1 ) { print o } }' INPUTFILE

sed -rn 'N;s/\n/ /;p' yourFile

cat file | paste -d' ' - -

What I recieved as output was:

USER abc  
_PASS 123  
USER efg  
_PASS 456  

Where _ is a simple space.

Badacadabra
  • 8,043
  • 7
  • 28
  • 49
  • http://stackoverflow.com/questions/10929453/read-a-file-line-by-line-assigning-the-value-to-a-variable this is how to read line into var, no write every two vars out to different file's one line – Drako May 15 '17 at 14:10
  • i can solve the problem doing 2 tmp file just with a grep and then make a paste command from the 2 files. but i'm trying a simple solution – Riccardo Gervasi May 15 '17 at 14:21
  • for me tmp would seem as simple solution, but good solution would be in python – Drako May 15 '17 at 14:36

4 Answers4

0

Easy with sed:

sed 'N;s/\n/ /' file

N appends the next line to the pattern space, and s/\n/ / replaces the newline character with a space.

Note that if the newline sequence is different, you have to change \n to the correct sequence: \r\n for Windows files, \r for old Mac file format...

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
0

cat file | paste -d' ' - - should work:

$ cat /tmp/t.txt
USER abc
PASS 123
USER efg
PASS 456
USER hil
PASS 789
$ cat /tmp/t.txt | paste -d' '  - -
USER abc PASS 123
USER efg PASS 456
USER hil PASS 789

If it does not, try running dos2unix on your file to make sure it has proper line endings.

damienfrancois
  • 52,978
  • 9
  • 96
  • 110
0

with paste:

paste -sd' \n \n' filename
tso
  • 4,732
  • 2
  • 22
  • 32
0

Just use awk:

$ awk '{printf "%s%s", $0, (NR%2 ? OFS : ORS)}' file
USER abc PASS 123
USER efg PASS 456
USER hil PASS 789

$ awk '{printf "%s%s", $0, (NR%3 ? OFS : ORS)}' file
USER abc PASS 123 USER efg
PASS 456 USER hil PASS 789

$ awk '{printf "%s%s", $0, (NR%6 ? OFS : ORS)}' file
USER abc PASS 123 USER efg PASS 456 USER hil PASS 789

Notice how you simply change the number from "2" to whatever you like to print however many lines you want concatenated? Try that with any other posted solution.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185