• 跳板机脚本ShellSshJumper中的linux命令 grep sed 的用法


    使用shell写了一个跳板机脚本ShellSshJumper

    这里总结记录下编写shell的注意点。

    主机配置保存在n.ini文件中如下:

    host=1.1.1.1
    port=22
    user=a
    passwd=b
    logintimes=0
    desc=abv
    create_time=2020-09-13 01:20:06
    update_time=2020-09-13 01:20:06

    使用sed读取配置文件

    涉及读取

      id=$1
      inifile='data/'$id'.ini'
      host=$(sed '/^host=/!d;s/^host=//' $inifile)
      port=$(sed '/^port=/!d;s/^port=//' $inifile)
      user=$(sed '/^user=/!d;s/^user=//' $inifile)
      passwd=$(sed '/^passwd=/!d;s/^passwd=//' $inifile)
      logintimes=$(sed '/^logintimes=/!d;s/^logintimes=//' $inifile)
      desc=$(sed '/^desc=/!d;s/^desc=//' $inifile)
      create_time=$(sed '/^create_time=/!d;s/^create_time=//' $inifile)
      update_time=$(sed '/^update_time=/!d;s/^update_time=//' $inifile)

    sed用法请去搜索,这里举例子解释下

    /^host=/!d;s/^host=//

    中间的“;”表示script分行,/^host=会匹配以host=开头的行,/!表示取反即不是host=开头的行,d表示操作删除。这一波操作下来就只剩host=1.1.1.1

    然后后面的s/^host=//中 s表示替换  ^host=代表被替换的部分,第二个/后面是空的表示要用空去替换   这一波操作下来就剩下1.1.1.1 

    这样解析host变量完成,其他的操作相同。

    使用grep只匹配到一个文件时显示文件名

    这里遇到一个坑:使用grep搜索命中多个文件时会返回文件名,但是如果只有一个文件就不会显示文件名,

    解决方案是grep -H  选项显示文件名

     使用sed更新配置项

    涉及更新  相同应用场景如 sed 匹配替换以某个字段开头,sed 替换 指定位置后所有字符

    像每次更新主机配置的host时:

    现在是  host=1.1.1.1

    要更新成 host=2.2.2.2

    命令如下

    newhost=2.2.2.2
    
    sed -i '/^host=/chost='$newhost 1.ini

    此处^host=表示匹配以host=开头的行   /c表示改变本行为后面的  host=$newhost

    sed -i '/^host=/chost='$host$inifile
  • 相关阅读:
    ArcObject GP 所有分析
    MVC Music Sotre 2
    ArcGIS Surface Analysis>Contour Error
    AE Contour和ContourAsPolyline
    解决了!我滴神哪!MarketPlace为什么手动下载安装部署提示invalid详解
    HTC 8X个人使用中常见问题解答
    关于模拟器Hyperv中的Wp8网络连接问题
    Lumia920价格
    Nokia House”或“NoHo
    {WP7/WP8·获取屏幕大小}
  • 原文地址:https://www.cnblogs.com/timseng/p/13661994.html
Copyright © 2020-2023  润新知