developer
developer

Reputation: 2050

replace a particular text in all the files using single line shell command

I have a renamed js file which I have to call in each of my php pages. Now I want to replace that old name with the new one using shell. what iam using is this:

sed -i ’s/old/new/g’ *

but this is giving the following error:

sed: -e expression #1, char 1: unknown command:

How can I do this replacement?

Upvotes: 43

Views: 52449

Answers (8)

Ziyad
Ziyad

Reputation: 157

I know I'm really late but still:

find . -type f -name "*.php"|xargs sed -i 's/old/new/g'

Upvotes: 9

shiramy
shiramy

Reputation: 833

For completeness, providing the OSX compatible version of the above accepted answer (to answer comment from @jamescampbell)

for i in *.php; do sed -i .orig 's/old/new/g' "$i"; done

This command creates .orig backup files.

Upvotes: 3

user7154703
user7154703

Reputation:

this one is very simple, without for or loop, and takes care of any number or nested directories

grep -rl 'oldText' [folderName-optional] | xargs sed -i 's/oldText/newText/g'

Upvotes: 12

K. Norbert
K. Norbert

Reputation: 10674

There are probably less verbose solutions, but here we go:

for i in *; do sed -i 's/old/new/g' "$i"; done

Mind you, it will only work on the current level of the file system, files in subdirectories will not be modified. Also, you might want to replace * with *.php, or make backups (pass an argument after -i, and it will make a backup with the given extension).

Upvotes: 33

Dennis Williamson
Dennis Williamson

Reputation: 360085

You are using Unicode apostrophes (RIGHT SINGLE QUOTATION MARK - U2019) instead of ASCII (0x27) apostrophes around your sed command argument.

Upvotes: 11

ghostdog74
ghostdog74

Reputation: 342363

sed -i.bak 's/old/new/g' *.php

to do it recursively

find /path -type f -iname '*.php' -exec sed -i.bak 's/old/new/' "{}" +;

Upvotes: 57

radio4fan
radio4fan

Reputation: 165

perl -pi -e 's/old/new/g' *.php

Upvotes: 4

lugte098
lugte098

Reputation: 2309

Try this:

ls | grep "php" > files.txt
for file in $(cat files.txt); do
    sed 's/catch/send/g' $file > TMPfile.php && mv TMPfile.php $file
done

Upvotes: -3

Related Questions