0

I'm trying to use the following command:

awk '/dev-api2\.company-private/{p=NR} p && NR==p+2 && /^HostName/{
$0="HostName 1.1.1.1"; p=0} 1' ~/.ssh/config > $$.tmp && mv $$.tmp ~/.ssh/config

Taken from this SO question.

Now I would like to replace the following:

dev-api2 with $shn
1.1.1.1 with $privateip

But now when I run the awk command it does nothing.

These are the values of the variables:

shn=dev-api2
privateip=3.3.3.3
0

2 Answers 2

2

You will need to use a dynamic regex instead of a literal one:

awk -v shn="$shn" -v privateip="$privateip" '
    $0 ~ shn "\\.company-private" { p = NR } 
    p && NR == p + 2 && /^HostName/ { $0 = "HostName " privateip; p = 0 } 1'

Instead of /regex/, use $0 ~ "string". The string will be evaluated and transformed into a regex, so you need to double-escape \\.

Sign up to request clarification or add additional context in comments.

Comments

-1

Use \":

awk "/dev-api2\.company-private/{p=NR} p && NR==p+2 && /^HostName/{
$0=\"HostName 1.1.1.1\"; p=0} 1" ~/.ssh/config > $$.tmp && mv $$.tmp
~/.ssh/config

1 Comment

Never use double quotes around a script in UNIX. It opens up your whole script to the shell for interpretation which makes it fragile and its output dependent on the environment you run it from. If you have a command cmd that takes a script as an argument and you want a shell variable to expand within it (which you don't even seem to be doing here so idk what you were trying to make happen), then you;d write it as cmd 'foo'"$var"'bar', not cmd "foo${var}bar" but you'd never do that with an awk script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.