Is this possible? I read somewhere that the following command would do it:
sed -e [command] [file]
but it appeared to do the same thing as just
sed [command] [file]
(it did not save the changes). Is there any way to do this using sed?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityIs this possible? I read somewhere that the following command would do it:
sed -e [command] [file]
but it appeared to do the same thing as just
sed [command] [file]
(it did not save the changes). Is there any way to do this using sed?
I think you are looking for -i
:
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if SUFFIX supplied)
For example:
$ cat foo.txt
hello world
$ sed -i 's/o/X/g' foo.txt
$ cat foo.txt
hellX wXrld
If you provide a suffix, it will create a backup file:
$ ls
foo.txt
$ sed -i.bak 's/o/X/g' foo.txt
$ ls
foo.txt foo.txt.bak
The input file is modified and a backup containing the original file data is created.
Also note that this is for GNU sed
, there are slight differences in format between different sed
implementations.
sed
does not do in-place editing. It creates a new file and overwrites the old one, the inode changes.
{ rm file; cmd > file; } < file
would lead to the conclusion that cmd reads and writes to the same file, which it does not. It's two distince files which just happen to have the same name. But I don't want to start a discussion here.
sed: 1: "foo.txt": invalid command code f
when running sed -i 's/o/X/g' foo.txt
. However, providing an extension, like sed -i .bak 's/o/X/g' foo.txt
works fine. Any ideas how to get it working without creating backup files?
Nov 29, 2018 at 19:53
sed -i '' 's/o/X/g' foo.txt
Nov 29, 2018 at 19:57
These solution works for HPUX (UNIX):
1.
{ rm test1.sh && awk '{gsub("Error", "NO_Error", $0); print}' > test1.sh; } < test1.sh
:
2.
perl -pi -e 's/Error/NO_Error/g' test1.sh
3.
sed 's/Error/NO_Error/g' test1.sh | tee test1.sh
-e
option is for executing multiple sed
commands
sed -e 's/linux/unix/' -e 's/os/OS/' file.txt
consider file.txt
as
linux os
then O/P is
unix os
-i
option saves changes permanently...
-e
flag stands for expression. You probably want the-i
flag which meansin-place
and I strongly recommend you to usesed -i.bak 's/../' filename