2

I am new to shell scripting and have a request to modify multiple files. I have
the input as below

#this is line1 for [email protected]        
test line 2  
test line 3  
this is line4 for [email protected]  
test line 5  
this is line6 for [email protected]

and need output like

#this is line1 for [email protected]   
test line 2  
test line 3   
##this is line4 for [email protected]  
this is line4 for [email protected]  
test line 5   
##this is line6 for [email protected]**  
this is line6 for [email protected]

i tried the below sed command, but not able to get the required output. It is not skipping the #line and appends it.

sed -e "/abc.com/{h;s/^/##/P;x;G; /^#/!s/abc.com/xyz.com/;}" file1

is there something i am missing???

Please help and any other suggestions would also be much appreciated.

Regards, Santosh

3
  • Can you more clearly show what your desired output is? Are the * part of the input and part of the desired output? Nothing in your example sed command skips lines with leading # for the first bit of work. Commented Jan 5, 2016 at 19:57
  • Etan - Thanks that is what exactly i am not able to isolate Commented Jan 5, 2016 at 20:06
  • I have modified the input and output accordingly now Commented Jan 5, 2016 at 20:14

3 Answers 3

1

This seems to be what you want

sed '/^[^#].*@abc.com/ {h; s/^/##/; p; g; s/abc.com/xyz.com/;}'

The equivalent awk:

awk '/^[^#].*abc.com/ {print "##" $0; sub(/abc.com/, "xyz.com")};1'

Pedantically, the dot should be escaped: abc\.com

Sign up to request clarification or add additional context in comments.

10 Comments

i tried this command but it gives me error sed: Function /^[^#].*@abc.com/ {h; s/^/##/; p; g; s/abc.com/xyz.com/} cannot be parsed.
Hmm, worked for me with GNU sed. Try adding a semicolon before the ending brace.
Thanks Glenn. It worked perfectly well after adding the semicolan
How to do case insensitive sed, i mean like how to replace ABC.com XYZ.com in the search
With GNU sed, you would use s/.../.../i, Otherwise you may have to s/[aA][bB][cC]\.com/xyx.com/
|
0
sed '
    /^#/n; 
    /.*abc.com/{
        h;  # hold this line to HOLD SPACE
        s/abc.com/xyz.com/;  # modify
        x;  # exchange PATTERN with HOLD
        s/^/##/;  
        G;  # get
    }
'

Comments

0

This might work for you (GNU sed):

sed 's/^\([^#].*\)abc\.com/##&\n\1xyz.com/' file

Only substitute lines which do not begin with a # and containd abc.com. The RHS of the substitution consists of the original line prepended by ## and a second line where the string abc.com is replace by xyz.com.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.