Monday, April 29, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 8398  / 3 Years ago, thu, may 6, 2021, 9:03:24

I have a configuration file and I want to replace a line containing a specific string, lets say test :



file.conf



aaa
bbb
ccc
// test
ddd
// test


My line of code is not working, I'm new to sed.



sed -i `s#^//[ 	]test#test#g'


Some guidance ?


More From » sed

 Answers
4

First of all, I'd recommend to avoid the use of -i as it will replace the files in-place without confirmation.



This is a working version of what you were trying to accomplish and outputs to the standard output (the terminal):



sed 's#^//[ 	]test$#test#g' file.conf
aaa
bbb
ccc
test
ddd
test


Optionally pipe it through less by appending | less to be able to paginate through large amounts of output.



The above is all very specific to the sequence of test, so to more generalize, you can try this:



sed 's#^//s(.*)$#1#g' file.conf


It will remove the // part and any whitespace until the actual text, whatever this text is.



If you like the result, you can add the -i flag again to replace the file.






To tell more about your attempt and explain why my example does work:



sed -i `s#^//[ 	]test#test#g'



  • You are using a backtick (`) which is interpreted by your shell rather than Sed. A simple single quote (') should have been used here probably.

  • The hashes (#) are your chosen delimiter, a good alternative to the common forward slash (/) as your match is about this same character and this avoids the need for escaping.

  • The pattern in the command s/regexp/replacement/ is a standard one as mentioned in the manpage, among many others: man 1 sed:




    s/regexp/replacement/



    Attempt to match regexp against the pattern
    space. If successful, replace that portion matched with replacement.
    The replacement may contain the special character & to refer to that
    portion of the pattern space which matched, and the special escapes
    1 through 9 to refer to the corresponding matching
    sub-expressions in the regexp.



  • rexexp in the above is a commonly used abbreviation for regular expressions.

  • The regular expression ^//[ ]test$ matches lines starting (^) with two forward slashes, followed by a space or a tab character, followed by the exact sequence test and a line ending ($).

  • The g flag is to do this operation in a global way as explained here.

  • An input file is missing and should be given after the Sed-command.


[#32931] Thursday, May 6, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ntlesslving

Total Points: 123
Total Questions: 109
Total Answers: 113

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
;