Save file after using sed command
Solution 1
Try this:
sed 's/yyyymmdd/YYYYMMDDHH24MISS/g' filename > changed.txt
Or, to keep the same filename:
sed 's/yyyymmdd/YYYYMMDDHH24MISS/g' filename > changed.txt && mv changed.txt filename
Solution 2
Your sed
command only sends its result to the standard output.
You would have to redirect it in a subsequent command (NOT in the same command, like sed 'sedcommand' file > file
, as this would erase the file before processing it).
You also can pipe the commands to ed
instead of using sed
:
for file in $filelist ; do
echo -e '%s/yyyymmdd/YYYYMMDDHH24MISS/g\nw' | ed $file
done
which substitutes on every line (%
) then, after a separating newline (\n
), writes the modified file in place (w
).
Solution 3
use -i
option with sed
command:
sed -ie 's/\('yyyymmdd'\)/\('YYYYMMDDHH24MISS'\)/g' filename
Related videos on Youtube
Hardik Kotecha
Updated on September 18, 2022Comments
-
Hardik Kotecha over 1 year
I am using following command to replace
yyyymmdd
toYYYYMMDDHH24MISS
in my file:sed -e 's/\('yyyymmdd'\)/\('YYYYMMDDHH24MISS'\)/g' filename
After I run the command in PuTTY, it displays the file with replaced values, but they do not reflect if I
more
the file.I tried using
-i
, but it sayssed: illegal option -- i
Can someone please suggest how do I replace the given code in multiple files and save them?
-
tachomi about 8 yearsHow you're using the
-i
option? Can you please update your question with the line that contains the-i
flag please? -
smw about 8 yearsThe
-i
option is not POSIX conformant: what system / flavor of Unix is thesed
command being run on (Linux? BSD? OSX?) -
terdon about 8 yearsAs steeldriver said, you need to tell us i) what operating system you are connecting to and ii) show us the exact command you ran. Also, this has nothing to do with your issue but you don't need the
\(
or the'
or any of that. Your command can be written simply assed -e 's/yyyymmdd/YYYYMMDDHH24MISS/g
(you can even omit the-e
on some systems).
-
-
Jeff Schaller about 8 yearssee also: unix.stackexchange.com/a/186126/117549
-
vonbrand about 8 years
sed(1)
anded(1)
are mostly compatible, command-wise. -
RalfFriedl over 4 yearsNot only did the OP write that the
-i
option is not supported, this example wouldn't do what you claim it does. -
Kusalananda over 4 yearsThe
-i
option (which the user has already said they can't use) takes an argument on most systems (even on Linux). That argument is the backup suffix to use for the original data when doing an in-place edit. You will notice that your command creates a file calledfilenamee
(note the extrae
at the end). Always test commands that you post here. -
Kirill Mikhailov over 2 yearssed -ie 'expression' file works fine on Ubuntu