Jimmy
Jimmy

Reputation: 12497

Awk match only when line starts with result

I have the following code:

function replaceappend() {
    awk -v old="$2" -v new="$3" '
        sub(old,new) { replaced=1 }
        { print }
        END { if (!replaced) print new }
    ' "$1" > /tmp/tmp$$ &&
    mv /tmp/tmp$$ "$1"
}

replaceappend "/etc/ssh/sshd_config" "Port" "Port 222"

It works perfectly but I am looking to modify it so that the awk command only finds a match if the line starts with that result. So if it's looking for the word "Port":

Port 123 # Test   <- It would match this one
This is a Port    <- It would not match this one

I've tried to look at other posts which ask about "Awk line starting with" such as this one, but I can't get my head around it:

awk, print lines which start with four digits

Upvotes: 2

Views: 454

Answers (1)

John1024
John1024

Reputation: 113924

In regular expressions, ^ matches only at the beginning of a line. Thus, to match Port only at the beginning of a line, write ^Port.

For example, lets create a file;

$ cat >testfile
Port 123 # Test   <- It would match this one
This is a Port    <- It would not match this one

Apply your function:

$ replaceappend testfile ^Port REPLACED

The result:

$ cat testfile 
REPLACED 123 # Test   <- It would match this one
This is a Port    <- It would not match this one

The GNU documentation has more information on the regular expressions supported by GNU awk.

Upvotes: 5

Related Questions