Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
I am writting a script that replaces a certain character in a string with a newline using sed command. I tried this :
cat t.txt | sed 's/href/\n/g' > test.txtbut it doesnt work. Anyone can help me out here?

This depends on the sed you are using, and in what context. I believe GNU's sed can do what you tried. More traditional sed (say OSF1) cannot, yet can quote an actual newline character. This means that at the prompt, you type the command right up to where you are going to insert a newline, then use the backslash to begin an escape, then press enter (sounds wierd but it works!) now you should have a "secondary prompt" and you complete the command line and press enter. This will look something like this at your terminal:
[bash] cat t.txt | sed 's/href/\
> /g' > test.txtNote that the greater-than symbol on the second line is not typed in, that is the default secondary prompt string, which shows up when the shell has determined that your pressing of the enter key meant that you needed an embedded (not terminating) End-of-line.
The rules are the same for a shell script, but be very careful that your editor does not append *any* bytes to the end of the line (particularly a space character gets stuck on sometimes). Here is what the code would look like in a script:#!/bin/bash
cat t.txt | sed 's/href/\
/g' > test.txtStrange at first but remember that End-of-line is just a byte, no different from any other character, its just our interactive software that treats it differently in certain circumstances.
If you wanted the same script to replace a pattern with 3 newlines, then you could do this:#!/bin/bash
cat t.txt | sed 's/href/\
\
\
/g' > test.txt

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |