Yes, using the w
command, or the w
flag to the s
command, both of which are specified by POSIX.
For example, with
sed -n 'w output.txt'
anything fed into sed
’s standard input will be written to output.txt
, with no output to sed
’s standard output (thanks to the -n
option). This can be combined with other commands to manipulate the pattern space before writing it out.
A few notes of warning and recommendations:
If the file name starts with a blank, use a ./
prefix:
sed -n 'w ./ output with blanks.txt'
If the file name contains newline characters, POSIXly, you can escape them with backslash, though it won't work with all sed
implementations (in particular, not with GNU sed
nor busybox sed
):
sed -n 'w ./output\
with\
newline.txt'
If it contains backslash characters, in some implementations (the POSIX ones above that support newlines in file names), you need to escape them with backslash:
sed -n 'w file\\with\\backslash.txt' # POSIX
sed -n 'w file\with\backslash.txt' # GNU
Also note that the output file will be created (or truncated) even if the input is empty or the w
command is never run like in:
sed 'd;w file'
Or
seq 20 | sed '/21/ w file'
You may want to use awk
instead to avoid this kind of problems
FILE=arbitrary-file-name awk '/100/ {print > ENVIRON["FILE"]}'
sed
's output from withinsed
(the accepted reply suggests that), then please change the title and the text of your question to reflect it; the argument to thew
command ofsed
doesn' t have to be a "text file"; it could be a character device, pipe, socket, etc. – Jan 10 '19 at 14:14sed
alone can produce a text file and if so how / when does that happen. If you still don't understand it then feel free to down-vote it. If you already did so, then enjoy your vote. – don_crissti Jan 10 '19 at 19:07