LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   replace a value in order (https://www.linuxquestions.org/questions/programming-9/replace-a-value-in-order-893845/)

sunilsagar 07-26-2011 08:28 AM

replace a value in order
 
I want to change the parameter for ThreadLimit for one file as shown below using sed. I want to ignore the commented line.
But the command I am using also executing with commented line.

# ThreadLimit: maximum setting of ThreadsPerChild
ThreadLimit 25

I want the desired output as

# ThreadLimit: maximum setting of ThreadsPerChild
#ThreadLimit 25
ThreadLimit 50

For this I am using command.

sed '/ThreadLimit/{;h;s/^/#/p;x;s/ .*/ 50/;}' test.txt.1 > test.txt

Please advise.

grail 07-26-2011 08:51 AM

So it is not good enough to just change 25 to 50? To fix your intended issue, tell sed the word you are looking for is at the start of the line.

sunilsagar 07-26-2011 12:26 PM

There is issue in doing so. The value is not fixed, it can be any value (eg . 10 , 15 or 19)
I just want to replace the value to 50 irrespective of the existing value.

crts 07-26-2011 12:55 PM

Try this:
Code:

sed -i.bak '/^ThreadLimit/ s/^/#/' filename
With the advice that has been given to you in your previous threads you should be able to append another line.

David the H. 07-26-2011 12:59 PM

As grail said, anchor the address match to the beginning of the line in order to only affect lines that start with "ThreadLimit".

But the command can be made much simpler in any case.

Code:

sed -r '/^ThreadLimit/ s/^(.*)/#\1\nThreadLimit 50/' file
Also, please use [code][/code] tags around your code, to preserve formatting and to improve readability.

grail 07-26-2011 03:19 PM

Or to take David's advice and only change any number:
Code:

sed '/^ThreadLimit/s/[0-9]+$/50/' file

Nominal Animal 07-26-2011 06:50 PM

I'd use
Code:

sed -e 's|^\([\t ]*ThreadLimit[\t ]\+\)\([-+]*[0-9]\+\)\(.*\)$|#&\n\1'"50"'|' -i file
For clarity, I separated the new parameter, 50, into a double-quoted part, so you can use e.g. a shell variable reference instead of a fixed constant.

The first subpattern will match optional whitespace, the keyword, and trailing whitespace. The second subpattern will match an integer parameter. The third subpattern will match everything trailing the parameter, if anything. The old line will be commented out, with the new one immediately following the commented out line.

If there are more than one ThreadLimit keyword (as the first token on a line, not commented out), the above will apply to each and every one.

sunilsagar 07-27-2011 11:13 PM

Thanks so much .. Nominal ..
It worked.


All times are GMT -5. The time now is 06:55 AM.