0

I want to ignore the beginning spaces in a file during pattern search and replacement. The final output doesn't need to have spaces. I have to match the whole line and replace with desired line. Tried different ways but the replacement is not happening as the white spaces are not matching.

Input file.txt:

Access /var/tmp/access.log  
    LogFormat "%h \"%r\" %>s %b\" common  
Error /var/tmp/err.log

Expected file.txt:

Access /var/tmp/access.log  
    LogFormat "%T %h \"%r\" %>s %b" common    
Error /var/tmp/error.log 

The below is what I tried and none works. The file remains same.

source1="LogFormat \"%h \\"%r\\" %>s %b\" common"
destination1="LogFormat \"%T %h \\"%r\\" %>s %b\" common"
sed -i "s|$source1|$destination1|" file.txt
sed -i "s|^(\s*)$source1|$destination1|" file.txt
sed -i "s|^\s*$source1|$destination1|" file.txt
sed -i "s|^[[:blank:]]$source1|$destination1|" file.txt
sed -i "s|^[[:blank:]]*$source1|$destination1|" file.txt

Please let me know how to achieve this. Thanks in advance.

3
  • [[::blank::]] lacks a quantifier so it's taken as just one space. Commented Oct 19, 2021 at 13:59
  • @pLumo Tried that too. It didn't work. I just updated the question with the command I tried.
    – LordG
    Commented Oct 19, 2021 at 14:05
  • I escaped the required chars and the variable looks OK. Sorry, I'm new to this site and unable to write comments in a clear format. # printf '%s\n' "$source1" LogFormat "%h \%r\ %>s %b" common
    – LordG
    Commented Oct 19, 2021 at 14:15

1 Answer 1

1

You have to double escape you source1 variable and use single quotes:

$ source1='LogFormat \\\"%h \\\\"%r\\\\" %>s %b\\\" common'
$ sed "s|$source1|$destination1|" file
Access /var/tmp/access.log  
    LogFormat "%T %h \"%r\" %>s %b" common  
Error /var/tmp/err.log

With the \s (in GNU sed):

$ sed "s|^\s*$source1|$destination1|" file 
Access /var/tmp/access.log  
LogFormat "%T %h \"%r\" %>s %b" common
Error /var/tmp/err.log
1
  • It worked. Thank you both.
    – LordG
    Commented Oct 19, 2021 at 14:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .