2

My file contents:

Google
Facebook
yahoo
cisco
juniper
oracle
firetide
attack

I wanted to convert the above words(column) into a row as shown below:

Google Facebook yahoo cisco juniper oracle firetide attack

NOTE : There should be a single space between each word.

Please suggest me a way to achieve this using sed or awk.

Thanks in advance.

Kumar
  • 729
  • 3
  • 11
  • 26
  • possible duplicate of [sed: How can I replace a newline (\n)?](http://stackoverflow.com/questions/1251999/sed-how-can-i-replace-a-newline-n) – Avinash Raj Dec 10 '14 at 07:55

6 Answers6

5

Using shell

If shell solutions are allowable, then try:

$ echo $(cat inputfile) 
Google Facebook yahoo cisco juniper oracle firetide attack

The above should work with any POSIX shell. With bash:

$ echo $(<inputfile) 
Google Facebook yahoo cisco juniper oracle firetide attack

Using sed

If we really must use awk or sed, then here is a sed solution:

$ sed ':a;N;$!ba; s/\n/ /g' inputfile
Google Facebook yahoo cisco juniper oracle firetide attack

The above reads the whole file in (:a;N;$!ba) and then replaces all newlines with spaces (s/\n/ /g).

If the input file might contain extra spaces at the beginning for end of a line, we can remove them:

$ sed ':a;N;$!ba; s/[[:space:]]*\n[[:space:]]*/ /g' inputfile
Google Facebook yahoo cisco juniper oracle firetide attack
John1024
  • 109,961
  • 14
  • 137
  • 171
2

Using awk

$ awk 'ORS=FS' inputFile
Google Facebook yahoo cisco juniper oracle firetide attack 

OR

Another variation would be

$ awk 1 ORS=' ' input
Google Facebook yahoo cisco juniper oracle firetide attack
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
1

Here is another way to do it:

xargs <file
Google Facebook yahoo cisco juniper oracle firetide attack

This also give a newline at the end unlike the awk posted.

Jotne
  • 40,548
  • 12
  • 51
  • 55
0

Using tr :

tr '\n' ' ' < File
Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27
0

With awk:

awk '{printf "%s ", $0}' file
pkalinow
  • 1,619
  • 1
  • 17
  • 43
0
sed -n '1h;1!H;${x;s/ *\n */ /gp;}' YourFile
  • replace starting / ending space and new line by a simple space (so any starting space will be removed ).
NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43