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
  • 709
  • 3
  • 10
  • 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
  • 103,964
  • 12
  • 124
  • 155
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
  • 25,677
  • 2
  • 36
  • 50
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
  • 39,326
  • 11
  • 49
  • 54
0

Using tr :

tr '\n' ' ' < File
Arjun Mathew Dan
  • 5,125
  • 1
  • 15
  • 27
0

With awk:

awk '{printf "%s ", $0}' file
pkalinow
  • 1,451
  • 16
  • 37
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,588
  • 1
  • 22
  • 41