Unix to inline replace all newlines in a file with \ n

sed 's/$/<br>/' mytext.txt 

worked, but displayed all this on the command line. I want it to just perform a replacement in the same file. Should I use another tool?

+6
command-line unix bash sed
source share
4 answers

If you have gnu sed, you can use the -i option, which will do the replacement.

 sed -i 's/$/<br>/' mytext.txt 

Otherwise, you will have to redirect to another file and rename it over the old one.

 sed 's/$/<br>/' mytext.txt > mytext.txt.new && mv mytext.txt.new mytext.txt 
+10
source share

Just for completeness. On Mac OS X (which uses the FreeBSD command), you must use the optional null string "" to edit in place without backing up:

 sed -i "" 's/$/<br>/' mytext.txt 

As an alternative to using sed to edit backups without space, you can use ed (1), which, however, reads the entire file into memory before running it.

 printf '%s\n' H 'g/$/s//<br>/g' ',p' | ed -s test.file # print to stdout printf '%s\n' H 'g/$/s//<br>/g' wq | ed -s test.file # in-place file edit 

For more information on ed (1) see

"Editing files using a text editor from scripts",

http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed

+3
source share

If you have an updated sed , just use sed -i or sed --in-place , which will modify the file itself.

If you need a backup, you need to specify a suffix for it. So sed -i.bak or sed --in-place=.bak will create a backup file with the suffix .bak .

Use it! Jokes aside! You will be very grateful for the first time you damage your file due to an erroneous sed command or an incorrect assumption about the data in the file.

+1
source share

Use the redirection symbol ie

 sed 's/$/<br>/' mytext.txt > mytext2.txt && mv mytext2.txt mytext.txt 
0
source share

All Articles