2

I am trying to search for a string and replace a text right next to it.. I know SED can be used to search for a string and replace it.

example given below.

Input file:

Some text 
Random option:"To Replace Text"

Output file:

Some text 
Random option:"Replaced Text"

I have tried the below.

grep 'option:' inputfile.txt > temp.txt -- so this gives the line with 'option:' to tempfile

$toReplace = cut -c 17-32 tempfile -- this gives the 'TO Replace Text'

sed 's/$toReplace/$toBeReplaced/' inputfile.txt > outfile.txt

I am sending the $toBeReplaced text from command line..

This works but I don't want to go with the cut command as the position may change in actual requirement.

Mahesh
  • 75
  • 2
  • 9
  • could you add what you've tried and what issue you faced with it? could you also add explanation regarding the rules on which the replacement has to be performed? for given example, there are various ways to do it.. one way is to search and replace the whole line.. – Sundeep May 02 '18 at 13:18
  • 1
    No, sed **cannot** be used to search for a string and replace it. sed can be used to search for a regexp and replace that with a string-containing-backreferences and if you want it to act as if it were really working with strings then you need to identify and replace all metacharacters (regexp, delimiter, and backreference - see https://stackoverflow.com/q/29613304/1745001) but you might be better off with simply using a tool that understands strings, e.g. awk. [edit] your question to clarify your requirements and provide a [mcve]. – Ed Morton May 02 '18 at 15:54

1 Answers1

0

This line may help you:

sed 's/\(Random option:"\)[^"]*/\1ReplacedTxt/' file
Kent
  • 189,393
  • 32
  • 233
  • 301