Reputation: 109
I encountered a problem in my program. I am using awk and I am trying to call a function in it.
function dots()
{
for ((i= 0 ; i < $1; i++)); do
echo "."
done
}
awk '{k=$1; sub(/[^ ]+ /,"__",$0); $1=$1; print $0 "\t:", (dots k) }'
Then I try to call the function and pass k
as the first argument (k
is a number). Is there a way to call a function in awk?
Upvotes: 5
Views: 4283
Reputation: 51
I also ran into similar problem and resolved the issue through writing awk function. We can't just call shell functions from awk. We need to write awk function inside the awk command as shown below:
awk '
function dots()
{
for ((i= 0 ; i < $1; i++)); do
echo "."
done
}
{k=$1; sub(/[^ ]+ /,"__",$0); $1=$1; print $0 "\t:", (dots k) }'
Upvotes: 1
Reputation: 72639
You just can't call shell functions from awk. You have to write an equivalent awk function, e.g. add this to your awk script:
function dots(n) {while(n-- > 0) print "."}
Upvotes: 9
Reputation: 203324
The way to efficiently create a string of n dots with awk is
function dots(n) { return gensub(/ /,".","g",sprintf("%*s",n,"")) }
The above uses GNU awk for gensub(), with other awks you can use a variable and gsub():
function dots(n, x) { x=sprintf("%*s",n,""); gsub(/ /,".",x); return x }
In the unlikely event that you really do want newlines after every .
then change / /,"."
to / /,".\n"
.
Upvotes: 3