./script_1:
#! /bin/bash
awk -v num=$1 'BEGIN {
n=num;
m=n=(num>=2)? n:2;
factors = "";
for(k=2; (m>1) && (k^2 <= n);)
{
if(int(m % k) != 0)
{
k++;
continue;
}
m/=k;
factors = (factors == "")? ("" k) : (factors "*" k);
}
if( (m > 1) && ( m < n) )
factors = factors "*" m;
print n, (factors=="")? "is a prime number":("=" factors)
}'
terminal:
aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1 2
2 is a prime number
aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1 3
3 is a prime number
aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1 4
4 =2*2
aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1 5
5 is a prime number
aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1 6
6 =2*3
2. Array Member Testing
awk needs contant time to do array member testing.
text2:
1 Chicago
4 Boston
3 Atlantic
./script_1:
#! /bin/bash
awk '{
cities[$1]=$2;
}
END {
for(i=1; i<=4; i++)
{
if (i in cities)
print i ":" cities[i];
}
}' text2
terminal:
aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1
1:Chicago
3:Atlantic
4:Boston
3. awk Flow Control
Skip further patterns for this record:
text 2:
start Chicago
skip Boston
end Atlantic
script_1:
After executing next, awk will ignore all remaining statements, including the "print $0"
#! /bin/bash
awk '/skip/ { next; print $0;}
{ print $0; } ' text2
terminal:
aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1
start Chicago
end Atlantic
=======================================Exit from current awk script:
text2:
start Chicago
process Los Angeles
exit Boston
end Atlantic
script_1:
#! /bin/bash
awk '/exit/ { exit 20; }
{ print $0; } ' text2
terminal:
aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1
start Chicago
process Los Angeles
aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ echo $?
20
No comments:
Post a Comment