Replace characters after match

I have a file with lines like:

foo find "https://localhost" "/website/foo" "this/that/the/other" "yes/no/maybe" -u admin -p admin > yes/no/maybe.txt

I'd like to replace the slashes in the last column with hyphens, like this:

foo find "https://localhost" "/website/foo" "this/that/the/other" "yes/no/maybe" -u admin -p admin > yes-no-maybe.txt

without affecting the other columns where I have slashes.

Try (untested)

awk '{gsub ("/", "-", $NF)} 1' file
1 Like

Thanks RudiC -- that works, someone else suggested:

awk '{gsub("/","-",$NF)}1'

the same it appears except for spaces. Both work.

Can you say what's going on here? Looks like number of fields NF and delimiters are being used along with gsub? (what's that), how is this applying only to the last column?

NF number of fields
$1 first field
$2 field 2
$NF last field
$(NF-1) second last field
sub() substitute
gsub() globally substitute, apply multiple subsequent substitutions
sub("/", "-", $NF) substitute a / with a - in the last field
gsub("/", "-", $NF) globally substitute a / with a - in the last field

1 Like

$NF is the last column in any record read from a file. It is an awk built-in variable. There are several of them. Since you want the last column changed you need to replace the / character with the - character. gsub , an awk builtin function, means substitute a pattern (1 or more characters). Use characters a new set of character(s) the replacement.

So using gsub on $NF does what you asked for.

See: AWK Built-in Variables