Home > Mobile >  sreach a pattern in file and insert/append a string in specefic position
sreach a pattern in file and insert/append a string in specefic position

Time:01-02

I am completely new to sed script. I have been researching how to add text to a file and managed to get the text I want adding to the correct line in the file but can not find a way to add it to the correct position! so the line I have in the text file looks like this

/^From: \s*(.*@)?(((test\.new\.com)))/ REJECT You are not me

and i want to get input from user and add input to above line, which result should be like below, user input is "test2.newer.com" and i want to add this string |(test2\.newer\.com)

/^From: \s*(.*@)?(((test\.new\.com)|(test2.\newer\.com)))/ REJECT You are not me

i try this but not working

read -p "Enter new domain: " newdomain
file="./testfile"
sed -i "/You are not me/ s/^\(.*\)\())\)/\1, |($newdomain)\2/" $file

how do I go about adding it to the correct position?

CodePudding user response:

With Escape a string for a sed replace pattern you can replace any line content that you want.

lineinfile='/^From: \s*(.*@)?(((test\.new\.com)))/ REJECT You are not me'
newcontent='/^From: \s*(.*@)?(((test\.new\.com)|(test2.\newer\.com)))/ REJECT You are not me'

ESCAPED_KEYWORD=$(printf '%s\n' "$lineinfile" | sed -e 's/[]\/$*.^[]/\\&/g');
ESCAPED_REPLACE=$(printf '%s\n' "$newlinecontent" | sed -e 's/[\/&]/\\&/g')
sed "s/$ESCAPED_KEYWORD/$ESCAPED_REPLACE/g"

CodePudding user response:

Using sed

$ newdomain="(test2.\\\newer\.com)"
$ sed "s|\([^)]*.[^)]*)\)\(.*\)|\1\|$newdomain\2|" input_file
/^From: \s*(.*@)?(((test\.new\.com)|(test2.\newer.com)))/ REJECT You are not me

  • Related