Linux bash: How to replace in file only if line meets additional condition?

Discussion in 'Site & Server Administration' started by postcd, Sep 1, 2016.

  1. #1
    Hello,

    i have a directory with many files, each file contains various HTML and also several occurences of ".com/" and i want to replace .com/ by .com/# BUT replacement should happen only if the line where is .com located do NOT contains phrasse: -t

    Please how to do it via Linux command line?

    Thank you
     
    postcd, Sep 1, 2016 IP
  2. samirj09

    samirj09 Well-Known Member

    Messages:
    335
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    125
    #2
    samirj09, Sep 3, 2016 IP
  3. postcd

    postcd Well-Known Member

    Messages:
    1,043
    Likes Received:
    9
    Best Answers:
    1
    Trophy Points:
    190
    #3
    One can try following (with caution and having backup):

    perl -i -pe 's/\.com\//$&#/ unless /-t/' *txt

    sed -e '/-t/! s:\.com/:.com/#:g' -i *.txt g means global, replace multiple occurences at one line
    sed -e '/-t/! s/\.com\//\.com\/#/' -i *.txt
     
    postcd, Sep 3, 2016 IP