枫叶饭团 写了:
都是寂寞惹的货啊

寂寞就来版聊吧,最近发现awk真的是个太好玩的东西了。
像咱这种对写shell脚本不熟的人来说,觉得awk真的很有用。
比如一些常见的命令都可以用awk实现:
代码: 全选
cat awk '{print}'
nl awk '{print NR,$0}'
去行号 awk '{sub(/^[0-9]+ /,"");print}'
wc -l awk 'END{print NR}'
sort awk '{A[NR]=$0}END{asort(x);for(i=1;i<=NR;i++)print A[ i]}'
echo awk 'BEGIN{for(i=1;i<ARGC;i++)printf("%s ",ARGV[i]);print}'
uniq awk '!A[$0]++'
也可以当计算器用:
代码: 全选
计算均值
awk '{S+=$0}END{print S/NR}'
另一种写法
awk 'BEGIN{for(i=1;i<ARGC;i++)s+=ARGV[ i];print s/(ARGC-1)}'
或者交互地计算表达式
awk '{gsub(/[^0-9()*/+-]/,"");sprintf("awk \"BEGIN{print %s}\"",$0)|getline;print}'
或者可以做GUI:
代码: 全选
#!/usr/bin/gawk -f
BEGIN{
"zenity --title \"Question\" --entry --text \"Your name?\""|getline;
gsub(/\"/,"\\\"");gsub(/\\/,"\\\\\\");
sprintf("zenity --info --text \"Hello, %s!\"",$0)|getline;
print;
}
或者可写HttpServer,然后浏览器访问“
http://127.0.0.1:8080”:
代码: 全选
#!/usr/bin/gawk -f
BEGIN{
port = "/inet/tcp/8080/0/0";
while(1){
print "HTTP/1.1 200 OK" |& port;
print "" |& port;
print "Hello World!" |& port;
while ((port |& getline) > 0 && !/^\r$/)
print;
close(port);
}
}
可以实现常见的数据结构,比如最简单Stack可以这样:
用数组——
代码: 全选
#!/usr/bin/gawk -f
BEGIN{
push(1);
push(2);
print pop();
push(3);
print pop();
print pop();
print pop();
}
function push(x){
stack[++stack["top"]] = x;
}
function pop( x){
if(stack["top"]==0){
print "<underflow>"
return;
}
x = stack[stack["top"]--]
return x
}
用链表——
代码: 全选
#!/usr/bin/gawk -f
BEGIN{
push(1);
push(2);
print pop();
push(3);
print pop();
print pop();
print pop();
}
function push(x){
n++;
node_next[n] = list_head;
node_data[n] = x;
list_head = n;
}
function pop( p,x){
if(!list_head){
print "<underflow>"
return;
}
x = node_data[list_head];
p = node_next[list_head];
delete node_data[list_head];
delete node_next[list_head];
list_head = p;
return x
}
或者链表——
代码: 全选
#!/usr/bin/gawk -f
BEGIN{
push(1);
push(2);
print pop();
push(3);
print pop();
print pop();
print pop();
}
function push(x){
n++;
list[n,"next"] = list["head"];
list[n,"data"] = x;
list["head"] = n;
}
function pop( p,x){
if(!list["head"]){
print "<underflow>"
return;
}
x = list[list["head"],"data"];
p = list[list["head"],"next"];
delete list[list["head"],"data"];
delete list[list["head"],"next"];
list["head"] = p;
return x
}
亦或者可以像顶楼里那样,
用正则表达式做词法解析,
用递归函数写递归下降的LL(1)文法解析器,
写写最简单的解释器或编译器应该都能使的。
咱这才是都是寂寞惹的货啊
