0

I am new to UNIX and am practising shell scripting. I have an application where I need string searching and replacement.

There are some lines in a file 1 and file 2. I have a search key word. If the key word is present in file 1 and file 2 then the sting after the key word in file 2 should be replaced with the string after the key word in file 1.

for example:

file 1:

abc def ghi jkl unix is the key

This file contains 3 lines and unix is the key

file 2 :

This is a sample sentence unix in the second file

This is line 2 and unix the new line in the second file

The key word is "unix".Here the string after unix in file file 1 is "is the key" so the string after the "unix" in file 2 i.e "in the second file" should be replaced with "is the key". so after the string reading and replacement the output of file should look like

file 1:

abc def ghi jkl unix is the key

This file contains 3 lines and unix is the key

file 2 :

This is a sample sentence unix is the key

This is line 2 and unix is the key

I used the following commands separately

 grep sed awk

But I am unable to figure out how can search and replacement can be combined. can any one tell me how the above can be done.any suggestions or help is appreciated.

Thanks in advance

0

This will work for the sample files you provided

replacement=$(sed -n 's/^.*unix\(.*$\)/\1/p' file1) sed -i "s/^\(.*unix\).*$/\1$replacement/" file2

Assumption is that the first file have the only one possible value of string after the unix keyword which can only be once per line.

Brief explanation of how it works, as requested.

those two lines supposed to be wrapped in a shell script. Regexp for the 1st sed extracts the part of the line that follows the unix keyword from the 1st file. replacemnet variable gets that part useing $() command substitution then in the second line that variable is used to replace the part of lines after the keyword in the second file.

  • can you give an example of how it works – user168983 Feb 8 '15 at 17:53
  • I believe the answer contains the example. Did you mean an explanation? – Tagwint Feb 8 '15 at 18:01
  • yes please. could you ? – user168983 Feb 8 '15 at 18:22
  • sure I've extended the answer with a brief explanation. – Tagwint Feb 8 '15 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.