11

I am using following command to replace yyyymmdd to YYYYMMDDHH24MISS 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 says

sed: illegal option -- i

Can someone please suggest how do I replace the given code in multiple files and save them?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Hardik Kotecha
  • 119
  • 1
  • 1
  • 3
  • 2
    How you're using the `-i` option? Can you please update your question with the line that contains the `-i` flag please? – tachomi Feb 04 '16 at 16:15
  • 4
    The `-i` option is not POSIX conformant: what system / flavor of Unix is the `sed` command being run on (Linux? BSD? OSX?) – steeldriver Feb 04 '16 at 16:27
  • 3
    As 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 as `sed -e 's/yyyymmdd/YYYYMMDDHH24MISS/g` (you can even omit the `-e` on some systems). – terdon Feb 04 '16 at 16:53

3 Answers3

17

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
terdon
  • 234,489
  • 66
  • 447
  • 667
AReddy
  • 3,122
  • 5
  • 35
  • 75
3

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).

gilgron31
  • 31
  • 2
3

use -i option with sed command:

sed -ie 's/\('yyyymmdd'\)/\('YYYYMMDDHH24MISS'\)/g' filename
Kevdog777
  • 3,194
  • 18
  • 43
  • 64
vineesh
  • 41
  • 1
  • Not only did the OP write that the `-i` option is not supported, this example wouldn't do what you claim it does. – RalfFriedl Nov 19 '19 at 06:26
  • The `-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 called `filenamee` (note the extra `e` at the end). Always test commands that you post here. – Kusalananda Nov 19 '19 at 06:48
  • sed -ie 'expression' file works fine on Ubuntu – Kirill Mikhailov Oct 28 '21 at 11:22