views:

42

answers:

4
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?

A: 

Use the redirection symbol i.e.

sed 's/$/<br>/' mytext.txt > mytext2.txt && mv mytext2.txt mytext.txt
tommieb75
+3  A: 

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
camh
whoops - of course! thanks for the quick reply!
DrMHC
+1  A: 

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.

paxdiablo
That's actually a new revelation. I was not aware of that at all. Thanks for your insight paxdiablo!
DrMHC
+1  A: 

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

bashfu