1753468 Members
4596 Online
108794 Solutions
New Discussion юеВ

sed question

 
SOLVED
Go to solution
Greg Stark_1
Frequent Advisor

sed question

We have a file containing multiple usernames on one line that we would like to insert returns after each username. For example, the file would change from this:

user1 user2 user3 user4

to this:
user1
user2
user3
user4

When we use the following sed command:
sed 's/ /\\n/g' file
we get this
user1\nuser2\nuser\nuser4

Any ideas on how to do this, or how to make sed not look print the \n litteraly?

Thanks in advance.
6 REPLIES 6
Robin Wakefield
Honored Contributor
Solution

Re: sed question

Hi Greg,

tr " " "\012" < filename

should do it.

Robin.
A. Clay Stephenson
Acclaimed Contributor

Re: sed question

Hi Greg,

Here's one way to do it in awk.

cat myfile | awk '{ n = split($0,arry); i = 1; while (i <= n) { printf("%s\n",arry[i]); ++i; } }' > newfile

All on one line.


Regards, Clay
If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: sed question

Hi Greg:

While I like 'tr' for this, here's another, short 'awk', given your input in a file called /tmp/myfile":

# awk '{for (i=1;i
Regards!

...JRF...

David Totsch
Valued Contributor

Re: sed question

How many "users" do you want per line? You could use paste(1) like this:

cat file | paste - - - -

would give you four entries per line.

-dlt-

Re: sed question

While tr or awk is probably better for this, here's how it can be done with sed:

sed 's/ //g'

You need a literal newline - sed doesn't understand \n in the replacement part. (If your shell is csh you'll need two \s in there.)

While at it, the shortest way to do it with awk is probably this:

awk 1 RS=' '

I wouldn't recommend that in production code though... (and it does result in an extra newline at the end of the file).

Re: sed question

Looks like itrc system ate the backslash-newline combination in my reply. Anyway, what you need is a backslash followed by literal newline in the right-hand side of the 's' command in sed (you can have newlines inside strings).