LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Sed scripting "how to replace value for only last part of a pattern " (https://www.linuxquestions.org/questions/linux-general-1/sed-scripting-how-to-replace-value-for-only-last-part-of-a-pattern-804254/)

alok.rhct 04-26-2010 07:58 AM

Sed scripting "how to replace value for only last part of a pattern "
 
Hi,
I am new to sed and i am trying to make some script for remediation purpose using it.

All i want is to replace some part of pattern.
eg:
$1=" alok 10"

i want to change 10 with any number/string so that result comes as "alok 20". Is it possible with sed ?

I am looking for code some thing related as :
echo "alok 10" |sed -ie "s/$1/$1 10/g

I know the above is wrong , its just for your reference.

Also, while replying kindly explain wherever is required.
I am sucked, waiting for your reply..

--Alok

pixellany 04-26-2010 08:12 AM

I do not understand what you are trying to do.

In your example, you first set a variable equal to "alok 10". Your SED code is perfectly valid, and will give you: "alok 10 10"

Note: don't use the -i flag unless you are operating on a file and want to edit it "in place". You also do not need the -e flag.

How about:
Code:

echo "alok 10" | sed 's/10/20/'

alok.rhct 04-28-2010 02:49 AM

Hi,
sorry for that i was not clear enough in my last post!!

Actually I am not sure about the value of "alok ", it may be 10 or may be 100 , all i am trying to do is ,
i want to replace some parameter in system files , take an example of sshd.conf.
i wan to search parameter "PermitrootLoging Yes" (default setting in sshd.conf) and replace it with "PermitrootLogin No."

Now as per the above example given by you, there can be n number of "Yes" in that file. and I can't change all yes to no.

So i want a solution to replace pattern based on position with sed.

Hope now you can understand me..

Thanks for your time..

pixellany 04-28-2010 07:10 AM

I think this is what you are saying:
"if 'pattern' is found, then replace 'word' with 'newword' "

For this, you can use the SED address feature----Using the above definition, it would be:

sed '/pattern/s/word/newword/' filename > newfilename

Here is a really good tutorial on SED: http://www.grymoire.com/Unix/Sed.html


All times are GMT -5. The time now is 05:51 PM.