Can sed save its output to a file?

> can do it.

echo "text" > file

tee can do it.

echo "test" | tee file

Can sed do it without using either of the above? Is it possible to save the output of a sed command to a file without using either > or tee?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

tee and > can be used for data redirection because these are meant to be used for data redirection in linux.

sed on the other hand is a stream editor. sed is not meant for data redirection as tee and > meant to be. However you can use conjunction of commands to do that.

use tee or > with sed

sed 's/Hello/Hi/g' file-name | tee file

or

sed 's/Hello/Hi/g' file-name > file

use sed with -i option

sed -i 's/Hello/Hi/g' file-name

the last one does not redirect, instead it will make changes in the file itself.

Method 2

sed has the w command that might do what you require:

w filename

Write the current pattern space to filename.

sed 'w file' on its own will have the same effect as tee file. If there are other sed commands, put the w last:

sed 's/This/That/;w file'

However, this won’t be affected by the -n/--quiet/--silent option. That only suppresses the content that would otherwise have gone to standard output.

Method 3

As ankidaemon correctly pointed out how we can save sed output to a file. I would like to add that if we are performing some operations on a file i.e replace and would like to save the output to the same file. There is a -i flag in sed which makes inplace edits possible. This however creates a backup file in the process if a suffix is provided as argument. If that’s not needed, that can be done by just passing empty filename or nothing to -i flag.

Example: sed -i "s/from/to/" file is inplace changing the file.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x