0

I have to implement an application in shell programming (Unix/Linux).

I have to search a word from a text file and replace that word with my given word. I have a knowledge on shell and still learning.

I am not expecting source code. Can anybody help me or suggest me or give me some similar solution....

J. Chomel
  • 8,193
  • 15
  • 41
  • 69
user1574726
  • 33
  • 1
  • 4

2 Answers2

0
cat abc.txt | grep "pattern" | sed 's/"pattern"/"new pattern"/g' 

The above command should work

Thanks,

Regards,

Dheeraj Rampally

fluter
  • 13,238
  • 8
  • 62
  • 100
Dheeraj R
  • 701
  • 9
  • 17
  • 2
    I smell a "useless use of cat" award...http://en.wikipedia.org/wiki/Cat_%28Unix%29#Useless_use_of_cat ;-) – Gary_W Mar 27 '14 at 15:26
0

Say you are looking for pattern in a file (input.txt) and want to replace it with "new pattern" in another (output.txt)

Here is the main idea, without UUOC:

<input.txt sed 's/"pattern"/"new pattern"/g' >output.txt

todo

Now you need to embed this line in your program. You may want to make it interactive, or a command that you could use with 3 parameters.


edit

I tried to avoid the use of output.txt as a temporary file with this:

<input.txt sed 's/"pattern"/"new pattern"/g' >input.txt

but it empties input.txt for a reason I can't understand. So I tried with a subshell, so:

echo $(<input.txt sed 's/pattern/"new pattern"/g')>input.txt

... but the echo command removes line breaks... still looking.


edit2

From https://unix.stackexchange.com/questions/11067/is-there-a-way-to-modify-a-file-in-place , it looks like writing to the very same file at once it not easy at all. However, I could do what I wanted with sed -i for only:

sed -i 's/pattern/"new pattern"/g' input.txt

From sed -i + what the same option in SOLARIS , it looks like there's no alternative, and you must use a temporary file:

sed 's/pattern/"new pattern"/g' input.txt > input.tmp && mv input.tmp input.txt
Community
  • 1
  • 1
J. Chomel
  • 8,193
  • 15
  • 41
  • 69