How to set a default value of a variable if the variable remain unset, below are the details
Like in bash :
x=1
echo ${x}
1
unset x
echo "${x:-I AM DEFAULT}"
How can this behavior achieved in awk:
Example:
-->echo "$x"
one two three four
foo bla2 bla3 bla4
bar bla7 bla8
Desired result:
echo "$x" |awk '..'
bla2 bla3 bla4 bla7 NA bla8
Current output:
echo "$x" |awk '/foo/{two=$2;three=$3;four=$4;next} /bar/{print two , three, four, $2,$3,$4} '
bla2 bla3 bla4 bla7 bla8
Cannot do like: (stupid act due to desperation) :
echo "$x" |awk '/foo/{two=$2;three=$3;four=$4;next} /bar/{print two , three, four, $2,${3:-NA},$4} '
OR
for awk $3 is bla8 so this will also not work.
echo "$x" |awk '/foo/{two=$2;three=$3;four=$4;next} /bar/{if(!length($3))print two , three, four, $2,$3,"NA",$4;print two , three, four, $2,$3,$4} '
bla2 bla3 bla4 bla7 bla8
Here you wouldn't know any mid value missing, since fields will just shift to left. There are two approaches you can take, either from number of fields NF set the missing values. Or, use some null value substitute. Here is a sample of the latter:
$ awk 'function nvl(x) {return x==""?"NA":x} {print nvl($1), nvl($2), nvl($3)}'
$ echo a b | awk ...
a b NA
$ echo a | awk ...
a NA NA
$ echo "" | awk ...
NA NA NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With