bash - Linux: why doesnt sed -e '1,244d' remove -
why doesn't sed -e '1,244d' remove first 244 lines of text file. i've used code many time albeit smaller line counts here copy of code:
sed -e '1,244d' /home/user/documents/working_files/storage/file.txt <> /home/user/documents/working_files/storage/file.txt
i test script in bash , nothing happens, run under sudo , displays script modified per script, not append/overwrite file, used "<>" option try script clear un-needed , not have append new file. appeciated. help
short answer
you can use
command < file | sponge file
so in case:
sed -e '1,244d' file | sponge file
sponge
(moreutils
) command soaks stdin
memory , when finished writes file
. enables 1 "inline" modifications.
fair warning inline modifications
first of warning: don't inline replacements. if server crashes in middle of process, file can corrupted, , case can have lost both original , new file. sponge
cannot undo effect: use sed -e '1,244d' file | sponge file
possible sed
finishes job, , sponge
starts writing file
. in middle of process machine crashes , content of original file gone , can recover part sponge
wrote.
you better use:
command < file > tempfile mv -f tempfile file
as @charlesduffy suggests.
which more atomic version of:
command < file > tempfile cp tempfile file rm tempfile
so in case machine crashes (for instance there power failure) @ part, have @ least or original file; or resulting file.
the problem diamond operator <>
the diamond operator has specification hard understand:
[j]<>filename # open file "filename" reading , writing, #+ , assign file descriptor "j" it. # if "filename" not exist, create it. # if file descriptor "j" not specified, default fd 0, stdin.
it means both reading , writing assigned stdin
, not reading stdin
, writing stdout
. diamond operator cannot used automatic inline replacement, unless program uses file descriptors bidirectionally.
bidirectional processing
as said, there exist utility programs sponge
allow store result temporary in memory , saves file when stdin
closes.
sed
specific inline edits
sed
has --in-place
flag:
-i[suffix], --in-place[=suffix] edit files in place (makes backup if suffix supplied)
so running:
sed -e '1,244d' -i file
you can inline modifications.
Comments
Post a Comment