1

In my bashscript I want Sed to find debug: Debug in a file ${SourceP} and if found delete that line and export to the environment Debug=Debug

sed -i '/debug: Debug/,+0 d' ${SourceP} && export Debug=Debug

But unfortunately, the Debug=Debug is getting exported even if the pattern is not found.

How can I achieve this: export Debug=Debug only if the pattern is found and delete the line.

Is it not possible to achieve with Sed?


I tried this with awk but this also doesn't work:

awk -i inplace '!/debug: Debug/' ${SourceP} && export Debug=Debug

Edit: I hope to search for debug: Debug exactly.

Porcupine
  • 1,892

2 Answers2

1

You need to export information out of the awk part somehow. Either you can export a variable, or use an exit status.

awk -i inplace 'BEGIN {err = 1}; {if (NR == 1 && /([[:space:]]|^)debug: Debug([[:space:]]|$)/) {err = 0} else {print}}; END {exit err}' ${SourceP} && export Debug=Debug

Explanation

  • BEGIN {err = 1}: initially, set the error status to 1.
  • Then if you are on the first line NR == 1 and && there is /([[:space:]]|^)debug: Debug([[:space:]]|$)/ on that line, set the error status to 0 (err = 0). Else, print all other lines. This regex is debug: Debug starting with either whitespace or at the start of the line, and ending with either whitespace or the end of the line.
  • When the awk script ends, exit with the error status {exit err}.
  • Hence, if /debug: Debug/ was found in the file, the error status would be 0 and the && would run.
Sparhawk
  • 19,941
  • Thank you! Also, how to limit awk to search debug: Debug only at the line number = 1 of the file?

    For example, If line 1 contains abcd debug: Debug xyz I expect it to work?

    – Porcupine Dec 02 '18 at 22:51
  • Your solution also accepts debug: DebugError? How can we search exactly for debug: Debug? – Porcupine Dec 02 '18 at 22:58
  • No worries. I basically followed your regex in the question. What exactly is the phrase you want? abcd debug: Debug xyz is okay, but debug: DebugError is not. So you want either whitespace or nothing adjacent to debug: Debug? – Sparhawk Dec 02 '18 at 22:59
  • Yes I hope whitespace or nothing adjacent to it – Porcupine Dec 02 '18 at 23:01
  • 1
    Okay, updated. The command is getting a bit massive with the edits, but hopefully you can still understand it! – Sparhawk Dec 02 '18 at 23:06
1
test "$(sed -i -e '/debug: Debug/{w /dev/fd/1' -e 'd}' "$SourceP")" && export Debug=Debug

Notes:

Writing ${SourceP} is pure mannerism; it's just as dangerous as the simple $SourceP. You want to quote it instead: "$SourceP" or "${SourceP}".

/dev/fd/1 is supported on most modern Unixes; sed -i and awk -i are GNU specific and highly unportable.