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

worked but output it all on the command line. I want it to just do the replacement WITHIN the specified file itself. Should I be using another tool?

4 Answers 4

11

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

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
0
3

Just for completeness. On Mac OS X (which uses FreeBSD sed) you have to use an additional null-string "" for in-place file editing without backup:

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

As an alternative to using sed for no-backup in-place file editing, you may use ed(1), which, however, reads the entire file into memory before operating on 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 with the ed text editor from scripts",

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

1

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

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

Use this! Seriously! You'll appreciate it a lot the first time you damage your file due to a mistyped sed command or wrong assumption about the data in the file.

1
  • 1
    That's actually a new revelation. I was not aware of that at all. Thanks for your insight paxdiablo!
    – DrMHC
    Aug 17, 2010 at 4:45
0

Use the redirection symbol i.e.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.