Question Detail
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?
Question Answer
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"
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
With
newdomain='test2\.newer\.com'
you can use the awk
command
awk -v repl="${newdomain//\\/\\\\}" '
BEGIN {OFS=FS=")))"}
/You are not me/ {$1=$1 ")|(" repl}
1
' "$file" > "$file".new && mv "$file".new "$file"
Explanation:
${newdomain//\\/\\\\}"
awk wants to treat the escape sequence \.
treated as a .
, so add backslashes.
BEGIN {OFS=FS=")))"}
Before parsing lines set “)))” as field separator (input and output).
/You are not me/
Change lines with this substring.
$1=$1 ")|(" repl'
Append )|(
and the string in repl
to $1
.
1
Print the line.
"$file" > "$file".new && mv "$file".new "$file"
Dpn’t edit in place but redirect to a new file and move that file to the original file when awk
succeeded.
thanks guys i find my problem and answer is like this:
read -p "Enter domain: " newdomain
sed -i "/You are not me/ s/\()))\)/)|$newdomain)))/' $file
but the output is like this:
/^From: \s*(.*@)?(((test\.new\.com)|(test2.newer.com)))/ REJECT You are not me
but i want this output:
/^From: \s*(.*@)?(((test\.new\.com)|(test2.\newer\.com)))/ REJECT You are not me