zoukankan      html  css  js  c++  java
  • 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重新初始化变量,为什么要初始化是因为下一次要用这个变量的时候,不能因为之前这个变量有值,影响下一次用,好让它继续下次的循环赋值。

  • 相关阅读:
    zendstudio xdebug 配置
    一键清除cvs/svn 目录
    mysql 引擎区分
    ngnix 配置
    linux下mysql安装、目录结构、配置
    tomacat 配置ssl协议
    HTML中<title>与<h1>区别
    HTML中<strong>与<b>,<em>与<i>标签的区别
    bootstrap的总结1
    JavaScript的DOM(文档对象)基础语法总结2
  • 原文地址:https://www.cnblogs.com/wangyuebo/p/5925266.html
Copyright © 2011-2022 走看看