0

we want to add the following lines before the match word - exec in launcher file

export  JAVA_HOME=/usr/jdk64/jdk1.8.0_112
export PATH=$PATH:$JAVA_HOME/bin

the launcher file

more  launcher
.
.
.
exec "$(dirname "$0")/launcher.py" "$@"

so we create the following sed line

 sed -i '/^exec/i export  JAVA_HOME=/usr/jdk64/jdk1.8.0_112\nPATH=${JAVA_HOME}/bin:$PATH' launcher 

the problem is that the second or the third time when we run the above sed line then sed append anew lines , so we get duplicate lines as

export  JAVA_HOME=/usr/jdk64/jdk1.8.0_112
PATH=${JAVA_HOME}/bin:$PATH
export  JAVA_HOME=/usr/jdk64/jdk1.8.0_112
PATH=${JAVA_HOME}/bin:$PATH
exec "$(dirname "$0")/launcher.py" "$@"

is it possible to tell sed to ignore appending when lines already exists? , ( or with perl one liner )

one option is to clean the lines with:

sed -i '/JAVA_HOME/d' launcher

and then

 sed -i '/^exec/i export  JAVA_HOME=/usr/jdk64/jdk1.8.0_112\nPATH=${JAVA_HOME}/bin:$PATH' launcher 

but want to know also if we can do it inside the above sed line

2

I'll simplify and call your exec line just "exec" and the prepending lines (with the exports) "pre1" and "pre2".

You could "skip" two lines on /pre1/ by loading them in the hold space and do the "empty" command b:

 sed '/pre1/{N;N;b};/exec/ipre1\npre2'

That way the command for /exec/ is only run when /pre1/ is not matched.

Assumes of course that you have either

 pre1
 pre2
 exec

or just

 exec

only and never "pre1" or "pre2" in other order, only one of them, or any of them somewhere else in the file.

3
  • 1
    Nice solution, if pre1 can't appear in another context in the file. Just one remark, that this is not portable, because most sed flavours will interpret everything after the b as branch label. So either do sed -e '/pre1/{N;N;b' -e '};/exec/ipre1\npre2' or use n: sed '/pre1/{n;n;n;};/exec/ipre1\npre2'
    – Philippos
    May 10 at 9:06
  • Good point, n is safer, especially since the script might be more complex.
    – FelixJN
    May 10 at 9:43
  • Feel free to include it in your answer
    – Philippos
    May 10 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.