zoukankan      html  css  js  c++  java
  • sed的一些使用技巧

    一、当一个文件里有两行相同的内容,但这时只想修改第一行的内容或者第二行的内容,而不是全部修改,以下例子说明下:

    1、修改匹配到第一行为port的内容(若要真修改前面记得-i):

    [root support-files]$ cat test.txt 
    [client]
    port            = 3306
    user            = mysql
    socket          =/data/mysql
    [mysqld]
    port            = 3306
    [root support-files]$ sed "1,/port/{s#=.*#=3307#}" test.txt |grep port
    port            = 3307
    port            = 3306

    2.修改匹配到的第二行内容,而不是第二行的内容,同样以port=3306为例:

    [root support-files]$ cat test.txt 
    [client]
    port            = 3306
    user            = mysql
    socket          =/data/mysql
    [mysqld]
    port            = 3306
    [root support-files]$ sed '/port/{x;s/^/./;/^.{2}$/{x;s/3306/3307/;b};x}' test.txt |grep port
    port            = 3306
    port            = 3307

    可以看到已经修改了吧,嘻^.^

    二、有时想MySQL里binlog后面的几个数字取出来,下面以mysql-bin.000036为例:

    [root mysql-5.5]$ echo "mysql-bin.000036" |cut -d . -f2 |sed 's/^0+//'
    36
    [root mysql-5.5]$ echo "mysql-bin.000036" |cut -d . -f2 |sed 's/^00*//g'
    36
    [root mysql-5.5]$ echo "mysql-bin.000036" |cut -d . -f2 |sed 's/0*//g'
    36

    嘿嘿,用awk也能实现:

    [root mysql-5.5]$ echo "mysql-bin.000036" |cut -d . -f2 |awk '{print $0+0}'
    36


    三、有时有一串数字,你可能用取前三位数,有时想取后三位数,反正想取前N个数或后N个数,都可以,下面举个例子:

    取前3个数字:

    [root ~]$ echo "11438010633"|sed 's/.*(...)/1/'
    633

    取后3个数字:

    [root ~]$ echo "11438010633"|sed 's/(...).*$/1/'       
    114

    四、有时一行有几个相同的字符,但有时只想修改第2个或者第3个时,如例子:

    下面是把第二个test修改为Linux

    [root ~]$ cat aa.sh 
    i am test a test,test is good boy test
    this is a test
    [root ~]$ sed 's/test/Linux/2' aa.sh i am test a Linux,test is good boy test this is a test

     第三个test修改掉为Linux的例子

    [root ~]$ cat aa.sh 
    i am test a test,test is good boy test
    this is a test
    [root ~]$ sed 's/test/Linux/3' aa.sh i am test a test,Linux is good boy test this is a test

    作者:陆炫志

    出处:xuanzhi的博客 http://www.cnblogs.com/xuanzhi201111

    您的支持是对博主最大的鼓励,感谢您的认真阅读。本文版权归作者所有,欢迎转载,但请保留该声明。

  • 相关阅读:
    C++类模板的三种特化
    构造函数抛异常
    ScrapySharp
    QtWebKit
    visual studio 插件
    asp.net 开源
    cfr
    eclipse icon
    JAD Java Decompiler
    Java Decompiler
  • 原文地址:https://www.cnblogs.com/xuanzhi201111/p/4118357.html
Copyright © 2011-2022 走看看