2

I'm trying to create a script to append oracleserver to /etc/hosts as an alias of localhost. Which means I need to:

  1. Locate the line that ^127.0.0.1 and NOT oracleserver$
  2. Then, append oracleserver to this line

I know the best practice is probably using negative look ahead. However, sed does not have look around feature: What's wrong with my lookahead regex in GNU sed?. Can anyone provide me some possible solutions?

Community
  • 1
  • 1
SexyNerd
  • 1,084
  • 2
  • 12
  • 21

3 Answers3

2
sed -i '/oracleserver$/! s/^127\.0\.0\.1.*$/& oracleserver/' filename
  • /oracleserver$/! - on lines not ending with oracleserver
  • ^127\.0\.0\.1.*$ - replace the whole line if it is starting with 127.0.0.1
  • & oracleserver - with the line plus a space separator ' ' (required) and oracleserver after that
Giuseppe Ricupero
  • 6,134
  • 3
  • 23
  • 32
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
2

Just use awk with && to combine the two conditions:

awk '/^127\.0\.0\.1/ && !/oracleserver$/ { $0 = $0 "oracleserver" } 1' file

This appends the string when the first pattern is matched but the second one isn't. The 1 at the end is always true, so awk prints each line (the default action is { print }).

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
0

I wouldn't use sed but instead perl:

Locate the line that ^127.0.0.1 and NOT oracleserver$

perl -pe 'if ( m/^127\.0\.0\.1/ and not m/oracleserver$/ ) { s/$/oracleserver/ }' 

Should do the trick. You can add -i.bak to inplace edit too.

Sobrique
  • 52,974
  • 7
  • 60
  • 101
  • If you are going to use perl, why not `perl -pe -i 's/^(127\.0\.0\.1.*)(?<!oracleserver)$/\1oracleserver/g filename`? – ndnenkov Dec 19 '15 at 23:16
  • Because I don't like trying to compress all my code into a regular expression unless it is essential. – Sobrique Dec 20 '15 at 05:19