shell脚本,awk常见初始化变量的题目。

文件 内容如下 

clone=line1
gb=line1
gi=line1
lib=line1
gb=line2
gi=line2
lib=line2
clone=line3
gb=line3
gi=line3
lib=line3
gb=line4
gi=line4
lib=line4

 

如何变为下面的内容

lib=line1 gi=line1 gb=line1 clone=line1 
lib=line2 gi=line2 gb=line2 
lib=line3 gi=line3 gb=line3 clone=line3 
lib=line4 gi=line4 gb=line4 

 

[root@localhost 09-30]# cat file
clone=line1
gb=line1
gi=line1
lib=line1
gb=line2
gi=line2
lib=line2
clone=line3
gb=line3
gi=line3
lib=line3
gb=line4
gi=line4
lib=line4
[root@localhost 09-30]# awk '{a=$0" "a}/^lib/{print a;a=""}' file
lib=line1 gi=line1 gb=line1 clone=line1
lib=line2 gi=line2 gb=line2
lib=line3 gi=line3 gb=line3 clone=line3
lib=line4 gi=line4 gb=line4
[root@localhost 09-30]# awk '{a=$0" "a}/^lib/{print a}' file
lib=line1 gi=line1 gb=line1 clone=line1
lib=line2 gi=line2 gb=line2 lib=line1 gi=line1 gb=line1 clone=line1
lib=line3 gi=line3 gb=line3 clone=line3 lib=line2 gi=line2 gb=line2 lib=line1 gi=line1 gb=line1 clone=line1
lib=line4 gi=line4 gb=line4 lib=line3 gi=line3 gb=line3 clone=line3 lib=line2 gi=line2 gb=line2 lib=line1 gi=line1 gb=line1 clone=line1
[root@localhost 09-30]#

 

 

 

解题思路:awk '{a=$0" "a}/^lib/{print a;a=""}' file

上面的结果是这个地方输出的 {a=$0" "a},这个结果只是循环进行赋值,当碰到^lib开头才进行输出 a的值 ,print a;a=""   第一个a是上面循环输出的值,最后的a是把变量a重新初始化变量,为什么要初始化是因为下一次要用这个变量的时候,不能因为之前这个变量有值,影响下一次用,好让它继续下次的循环赋值。

 

posted on 2016-10-01 00:12  王月波  阅读(1351)  评论(0编辑  收藏  举报

导航