AWK returns number instead of string for sub/gsub

Viewed 1847

I am parsing the output of a command, example:

0. BP-726162639-172.16.2.40-1425055855614:blk_1724943006_651672912 len=39498 Live_repl=3 [DatanodeInfoWithStorage[172.16.2.168:50010,DS-fbfe96c7-82c7-4be3-b056-5a74b3fa2f4b,DISK], DatanodeInfoWithStorage[172.16.2.170:50010,DS-5459e7a0-2874-4a84-b4a4-e7fc84be391f,DISK], DatanodeInfoWithStorage[172.16.2.162:50010,DS-86792af4-6db8-478a-97c7-2b6560f2cc19,DISK]]

The first sub works as expected but the subs after that fail:

awk '{print "block # : " gsub(/\./,"",$1) $2 " :: " sub(/len=/,"a",$3) " :: " $4}'

This prints:

block # : 1BP-726162639-172.16.2.40-1425055855614:blk_1724943006_651672912 :: 1 :: Live_repl=3

I am not sure why this is happening. Is it not ok to use multiple subs?

After understanding @ken's answer it is obvious that I need to do the substitution at the beginning and just use $1 $2 etc later in the print.

2 Answers

both gsub and sub worked in your codes.

The two functions will do substitutions, and return the count, how many substitutions were done. (not the string after replacement).

So the 1 before BP-... is from gsub and the other 1 between :: s, is from sub().

To highlight the answer, simply use the variable again after substituting it:

echo foo-default | awk '{ sub("-default", "", $1); printf "(%s)", $1 }'
(foo)
Related