1833758 Members
2616 Online
110063 Solutions
New Discussion

Pattern replacing

 
SOLVED
Go to solution
M.Thomas
Frequent Advisor

Pattern replacing

I want to replace OLDPATTERN with NEWPATTERN in some files using scripting without changing the file name. (I don’t want to redirect to another file, I want to do that in same file)


Thanks in advance

Regards
Thomas
9 REPLIES 9
Suraj Singh_1
Trusted Contributor
Solution

Re: Pattern replacing

for _file in file1 file2 file3 ...
do
perl -pi -e 's/OLDPATTERN/NEWPATTERN/g' ${_file}
done
What we cannot speak about we must pass over in silence.
Suraj Singh_1
Trusted Contributor

Re: Pattern replacing

Or in a single line:

perl -pi -e 's/OLDPATTERN/NEWPATTERN/g' file1 file2 file3 ...
What we cannot speak about we must pass over in silence.
Karsten Löperick
Valued Contributor

Re: Pattern replacing

Hello Thomas,

try this on a posix-shell:

sed s/oldpattern/newpattern/ file | tee file

After applying the sed command file should be contain the newpattern. But remember it is just a single line substitution.

Greetings
Karsten
Nothing is impossible
Dennis Handly
Acclaimed Contributor

Re: Pattern replacing

>Karsten: sed s/oldpattern/newpattern/ file | tee file

The tee(1) is going to writing to the same file that sed(1) is reading.
Karsten Löperick
Valued Contributor

Re: Pattern replacing

Hi Dennis, Thomas

thats right- if you want to shorten the sed script a bit, you can of course remove the filename after the tee command.
sed ... | tee its enough.

Greetings
Karsten
Nothing is impossible
Dennis Handly
Acclaimed Contributor

Re: Pattern replacing

>Karsten: if you want to shorten the sed script a bit, ... remove the filename after the tee

I'm not sure of your point but my point was that you can't use tee(1). You must write to a new file. And if you remove the file name after tee(1), why use tee(1)?
M.Thomas
Frequent Advisor

Re: Pattern replacing

Hi All,

Thanks for your quick response


Regards
Thomas
Karsten Löperick
Valued Contributor

Re: Pattern replacing

Hi Dennis,

hmm - it works fine for me in both ways. I do the sed with the file - and then reading the same file with more/cat. Everything is replaced in the same file without any redirection ( see man tee - the tee command transcribes the standard input to the standard output and makes copies in the files )

Greetings

Karsten
Nothing is impossible
Dennis Handly
Acclaimed Contributor

Re: Pattern replacing

>Karsten: ... Everything is replaced in the same file without any redirection (the tee command transcribes the standard input to the standard output and makes copies in the files)

I'm suggesting it may not work depending on the size of the file and the size of the stdio buffers and how many chars you are inserting/deleting with sed. In general, writing to the file you're reading isn't a good idea. Especially by separate processes that don't know this is occurring.