0
sed -i s/oldstr/newstr/g

I want to replace all old string with new string in a directory. When I executed this command, It shows all strings are changed to new string on console. But when I entered into file and checked, Old string still remains same. Please help to figure the issue

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
Krish
  • 1
  • 3
  • Welcome to stack overflow, what did you pass to this `sed` command ? Which Input_file(s) or `*` you have put please let us know on same. – RavinderSingh13 Oct 28 '17 at 15:25
  • depending on your sed version, you may have to use `-i` option differently - see https://stackoverflow.com/questions/5694228/sed-in-place-flag-that-works-both-on-mac-bsd-and-linux.... also, as a good practice, use single quotes around the command `sed -i.bkp 's/oldstr/newstr/g'` – Sundeep Oct 28 '17 at 15:32
  • Did you try `cat file | sed -i 's/oldstr/newstr/g'`? Use the file as an argument `sed -i 's/oldstr/newstr/g' file` – Walter A Oct 28 '17 at 18:38

2 Answers2

0
#> sed -i \.orig 's/old/new/g'  file

That should be the same as:

#> mv file file.orig 

#> sed 's/old/new/g' file.orig > file. 
JDQ
  • 111
  • 4
  • Thanks. Why is sed ‘s/old/new/g’ * not changing the string in all files(apparently sed ‘s/old/new/g’ file.orig > file works fine) – Krish Oct 29 '17 at 06:24
  • Might be to prevent us from trashing a bunch of files and having to access backups...d8) – JDQ Oct 29 '17 at 06:55
0

In case you are in macos you could try:

sed -i '' 's/oldstr/newstr/g' your-file

From the man:

Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved.

So by using -i '' it will not create a backup and apply changes to your file.

to keep a backup this could be used:

sed -i.bak 's/oldstr/newstr/g' your-file

To replace the oldstr in multiple files you could use this:

perl -pi -e 's/oldstr/newstr/g' *

To keep a backup:

perl -i.bak -p -e 's/oldstr/newstr/g' *
nbari
  • 25,603
  • 10
  • 76
  • 131