Reputation: 3850
I use an alias named ThousandsDotting
that add points .
each 3 numbers (the classic dot for thousands), so 100000
become 100.000
.
It works fine in the shell, but not in a function.
Example file example.sh
:
#!/bin/bash
function test() {
echo "100000" | ThousandsDotting
}
alias ThousandsDotting="perl -pe 's/(\d{1,3})(?=(?:\d{3}){1,5}\b)/\1./g'"
test
If I run it, this is what I get:
$ ./example.sh
example.sh: line 3: ThousandsDotting: command not found.
What is the correct way to pipe (or use it without pipes, whatever) stdout data to this perl
command in a function for my Bash shell script?
Upvotes: 2
Views: 655
Reputation: 1364
Aliases are not expanded in bash and can't be used as macros. You can enable them, and for more information look at the eternal guide to BASH http://tldp.org/LDP/abs/html/aliases.html.
You can achieve the same as macros with the normal tools provided by bash:
#!/bin/bash
function test() {
echo "100000" | perl -pe 's/(\d{1,3})(?=(?:\d{3}){1,5}\b)/\1./g'
}
test
You can improve this by making the function capable of having parameters: this way you can pass any argument to the function test
obtaining exactly what you would have had by using an alias:
#!/bin/bash
function test() {
perl -pe 's/(\d{1,3})(?=(?:\d{3}){1,5}\b)/\1./g' "$1"
}
test 100000
Upvotes: 0
Reputation: 88583
alias
works in an interactive bash
. Change
#!/bin/bash
to
#!/bin/bash -i
From man bash
:
If the -i option is present, the shell is interactive.
Upvotes: 1
Reputation: 4649
Alias is limited by default in bash, so just enable it.
#!/bin/bash
shopt -s expand_aliases
alias ThousandsDotting="perl -pe 's/(\d{1,3})(?=(?:\d{3}){1,5}\b)/\1./g'"
function test() {
echo "100000" | ThousandsDotting
}
test
output
100.000
Upvotes: 3
Reputation: 785068
In BASH Aliases are not inherited.
Better you create a function instead:
ThousandsDotting() { perl -pe 's/(\d{1,3})(?=(?:\d{3}){1,5}\b)/\1./g' "$1"; }
You can then use it as process substitution:
ThousandsDotting <(echo "100000")
100.000
Upvotes: 2