美文网首页
source code for shell

source code for shell

作者: rhc2008 | 来源:发表于2023-11-11 22:52 被阅读0次
    变量替换总结
    # 字符串匹配(1,2 从前往后; 3,4从后往前)
    1、${变量#匹配规则}            # 从头开始匹配,最短删除
    2、${变量##匹配规则}           # 从头开始匹配,最长删除
    3、${变量%匹配规则}            # 从尾开始匹配,最短删除
    4、${变量%%匹配规则}           # 从尾开始匹配,最长删除
    # 字符串替换 
    5、${变量/旧字符串/新字符串}     # 替换变量内的旧字符串为新字符串,只替换第一个
    6、${变量//旧字符串/新字符串}    # 替换变量内的旧字符串为新字符串,全部替换
            
    例子1:
    variable_1="I love you,Do you love me"
    var1=${variable_1#*ov}      # e you,Do you love me
    var2=${variable_1##*ov}     # e me
    var3=${variable_1%ov*}    # I love you,Do you l
    var4=${variable_1%%ov*}    # I l
            
    var5=${PATH/bin/BIN}    #/usr/local/sBIN:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/root/.local/bin
    var6=${PATH//bin/BIN}   #/usr/local/sBIN:/usr/local/BIN:/usr/sBIN:/usr/BIN:/sBIN:/BIN:/usr/games:/usr/local/games:/snap/BIN:/root/.local/BIN
    
    
    字符串处理总结:
    1、计算字符串长度
    方法一:${#string}
    方法二:expr length $string
            
    例子:
    var1="Hello World"
    len=${#var1}
    len=`expr length "$string"`
                
                
    2、获取字符索引位置  
    方法:expr index "$string" substr
            
    例子:
    var1="quicstart is a app"
    ind=`expr index "$var1" start`   # 5
    ind=`expr index "$var1" unique`   # 1                   
    3、获取子串长度    
    方法:expr match "$string" substr
            
    例子:
    var1="quicstart is a app"
    sub_len=`expr match "$var1" app`  # 0 ,("app"匹配的字符要从第一个位置开始)
                    
    4、抽取字符串中的子串 
    方法一:
    (1)、${string:position}
    (2)、${string:position:length}
    (3)、${string: -position} 或者 ${string:(position)}
    
    方法二:
    expr substr $string $position $length                   
    例子:
    var1="kafka hadoop yarn mapreduce"
    substr1=${var1:10}  #op yarn mapreduce
    substr2=${var1:10:6}    #op yar
    substr3=${var1: -5} #educe
    substr4=${var1: -10:4}  #map                
    substr5=`expr substr "$var1" 5 10`  #a hadoop y
    注意:使用expr,索引计数是从1开始计算;使用${string:position},索引计数是从0开始计数
    
    #!/bin/bash
    
    
    需求描述:
    变量string="Bigdata process framework is Hadoop,Hadoop is an open source project"
    执行脚本后,打印输出string字符串变量,并给出用户以下选项:
    (1)、打印string长度
    (2)、删除字符串中所有的Hadoop
    (3)、替换第一个Hadoop为Mapreduce
    (4)、替换全部Hadoop为Mapreduce
    用户输入数字1|2|3|4,可以执行对应项的功能;输入q|Q则退出交互模式
    
    思路分析:
    1、将不同的功能模块划分,并编写函数
       function print_tips
       function len_of_string
       function del_hadoop
       function rep_hadoop_mapreduce_first
       function rep_hadoop_mapreduce_all
    
    2、实现第一步所定义的功能函数
    function print_tips
    {
    echo "******************************"
    echo "(1) 打印string长度"
    echo "(2) 删除字符串中所有的Hadoop"
    echo "(3) 替换第一个Hadoop为Mapreduce"
    echo "(4) 替换全部Hadoop为Mapreduce"
    echo "******************************"
    }
    
    function len_of_string
    {
        echo "${#string}"
    }
    
    function del_hadoop
    {
       echo "${string//Hadoop/}"
    }
    
    function rep_hadoop_mapreduce_first
    {
        echo "${string/Hadoop/Mapreduce}"
    }
    
    function rep_hadoop_mapreduce_all
    {
       echo "${string//Hadoop/Mapreduce}"
    }
    
    3、程序主流程的设计
    代码:
    #!/bin/bash
    #
    string="Bigdata process framework is Hadoop,Hadoop is an open source project"
    function print_tips
     {
      echo "******************************"
      echo "(1) 打印string长度"
      echo "(2) 删除字符串中所有的Hadoop"
      echo "(3) 替换第一个Hadoop为Mapreduce"
      echo "(4) 替换全部Hadoop为Mapreduce"
      echo "******************************"
    }
    
    function len_of_string
     {
      echo "${#string}"
    }
    
    function del_hadoop
     {
      echo "${string//Hadoop/}"
    }
    
    function rep_hadoop_mapreduce_first
     {
         echo "${string/Hadoop/Mapreduce}"
     }
    
    function rep_hadoop_mapreduce_all
    {
        echo "${string//Hadoop/Mapreduce}"
    }
    
    while true
    do
        echo "【string=$string】"
    echo
    print_tips
    read -p "Pls input your choice(1|2|3|4|q|Q): " choice
    case $choice in
                1)
                  len_of_string
                  ;;
                2)
                  del_hadoop
                  ;;
                3)
                  rep_hadoop_mapreduce_first
                  ;;
                4)
                  rep_hadoop_mapreduce_all
                  ;;
                q|Q)
                    exit
                    ;;
                *)
                  echo "Error,input only in {1|2|3|4|q|Q}"
                  ;;
    esac
    done
    
    
    命令替换总结:
    有两种方法:      
    方法一:`command`
    方法二:$(command)
                
    例子1:
    获取系统得所有用户并输出    
    #!/bin/bash
    #   
    index=1         
    for user in `cat /etc/passwd | cut -d ":" -f 1`
    do
        echo "This is $index user: $user"
        index=$(($index + 1))
    done
    
    例子2:    
    根据系统时间计算今年或明年
    echo "This is $(date +%Y) year"
    echo "This is $(($(date +%Y) + 1)) year"
                
    例子3:    
    根据系统时间获取今年还剩下多少星期,已经过了多少星期
    date +%j
    echo "This year have passed $(date +%j) days"
    echo "This year have passed $(($(date +%j)/7)) weeks"
    echo "There is $((365 - $(date +%j))) days before new year"
    echo "There is $(((365 - $(date +%j))/7)) days before new year"
                
    例子4:
    判定nginx进程是否存在,若不存在则自动拉起该进程
    #!/bin/bash
    #   
    nginx_process_num=$(ps -ef | grep nginx | grep -v grep | wc -l) 
    if [ $nginx_process_num -eq 0 ];then
        systemctl start nginx
    fi
                
    总结:
    ``和$()两者是等价的,但推荐初学者使用$(),易于掌握;
    缺点是极少数UNIX可能不支持,但``都是支持的
    $(())主要用来进行整数运算,包括加减乘除,引用变量前面可以加$,也可以不加$    
    $(( (100 + 30) / 13 ))      
    num1=20;num2=30
    ((num++));
    ((num--))
    $(($num1+$num2*2))
    
    有类型变量总结:
    1、declare -r    #声明变量为只读类型
            
    declare -r var="hello"
    var="world"  -bash: var: readonly variable
                
    2、declare -i    #声明变量类型为整型      
    num1=2001
    num2=$num1+1
    echo $num2
                
    declare -i num2
    num2=$num1+1
    echo $num2
            
    3、declare -f        在脚本中显示定义的函数和内容      
    4、declare -F        在脚本中显示定义的函数
    5、declare -a
            
    array=("jones" "mike" "kobe" "jordan")          
    输出数组内容:                                                     
    echo ${array[@]}    输出全部内容
    echo ${array[1]}    输出下标索引为1的内容
                
    获取数组长度:                                                                 
    echo ${#array}  数组内元素个数
    echo ${#array[2]}   数组内下标索引为2的元素长度
                            
    给数组某个下标赋值:                                              
    array[0]="lily" 给数组下标索引为1的元素赋值为lily
    array[20]="hanmeimei"   在数组尾部添加一个新元素
    删除元素:                                                           
    unset array[2]  清除元素
    unset array 清空整个数组
                            
    分片访问:                                                           
    ${array[@]:1:4} 显示数组下标索引从1开始到3的3个元素,不显示索引为4的元素
                            
    内容替换:                                                           
    ${array[@]/an/AN}   将数组中所有元素内包含kobe的子串替换为mcgrady
    数组遍历:
    for v in ${array[@]}
    do
     echo $v
    done
                                                                    
    6、declare -x
    声明为环境变量,可以在脚本中直接使用
    取消声明的变量:
    declare +r
    declare +i
    declare +a
    declare +X
    
    command1 && command2 && command3 ...
    &&左边的命令(命令1)返回真(即返回0,成功被执行)后,&&右边的命令(命令2)才能够被执行;换句话说,“如果这个命令执行成功&&那么执行这个命令”
    command1 || command2
    ||则与&&相反。如果||左边的命令(command1)未执行成功,那么就执行||右边的命令(command2);或者换句话说,“如果这个命令执行失败了||那么就执行这个命令
    
    is_nginx_running && echo "running" || echo "stoped"
    is_nginx_running 为真(命令返回值 $? == 0)  输出:running, 否则(命令返回值 $? == 1)输出:stoped
    
    bash数学运算之expr:
            num1=20
            num2=100
            expr $num1 \| $num2
            expr $num1 \& $num2
            expr $num1 \< $num2
            expr $num1 \< $num2
            expr $num1 \<= $num2
            expr $num1 \> $num2
            expr $num1 \>= $num2
            expr $num1 = $num2
            expr $num1 != $num2
            expr $num1 + $num2
            expr $num1 - $num2
            expr $num1 \* $num2
            expr $num1 / $num2
            expr $num1 % $num2
            
            
    练习例子:       
    提示用户输入一个正整数num,然后计算1+2+3+...+sum的值;必须对num是否为正整数做判断,不符合应当允许再此输入
    #!/bin/bash
    #
    while true
    do
        read -p "Pls enter a positive integer(num>0): " num
            expr $num + 1 &> /dev/null
        if [ $? -ne 0 ];then
            echo "Error,You must input a interger"
            continue
        else
            if [ `expr $num \> 0` -ne 1 ];then
                echo "Error,You must input a postive interger"
                   continue
            else
                sum=0
                for((i=0;i<=$num;i++))
                do
                    sum=`expr $sum + $i`
                done
                echo "1+2+3+4+5+...+$num=$sum"
            fi
        fi
    done
    
    bash数学运算之bc:
    脚本中使用bc运算的语法:   
    echo "options;expression" | bc          
    num1=23.5
    num2=50
    var1=`echo "scale=2;$num1 * $num2" | bc`
    
    定义函数:
    需求描述:写一个监控nginx的脚本;如果Nginx服务宕掉,则该脚本可以检测到并将进程启动;如果正常运行,则不做任何处理
    #!/bin/bash
    #
    this_pid=$$
    function nginx_daemon
    {
    status=$(ps -ef | grep -v $this_pid | grep nginx | grep -v grep &> /dev/null)
    if [ $? -eq 1 ];then
        systemctl start nginx && echo "Start Nginx Successful" || echo "Failed To Start Nginx"
    else
        echo "Nginx is RUNNING Well"
        sleep 5
    fi
    }
    
    while true
    do
        nginx_daemon
    done
    
    可选:在终端命令行定义函数:  
    在脚本中定义好disk_usage函数,然后直接使用. test.sh,再使用declare -F查看,是否可以列出disk_usage函数
                
    function disk_usage
    {
    if [ $# -eq 0 ];then
        df
    else
        case $1 in
        -h)
            df -h
            ;;
        -i)
             df -i
             ;;
        -ih|-hi)
              df -ih
               ;;
        -T)
             df -T
             ;;
        *)
            echo "Usage: $0 { -h|-i|-ih|-T }"
             ;;
        esac
    fi
    }   
    
    
    • 在Linux系统中0 1 2是一个文件描述符
    名称 代码 操作符 Java中表示 Linux 下文件描述符(Debian 为例)
    标准输入(stdin) 0 < 或 << System.in /dev/stdin -> /proc/self/fd/0 -> /dev/pts/0
    标准输出(stdout) 1 >, >>, 1> 或 1>> System.out /dev/stdout -> /proc/self/fd/1 -> /dev/pts/0
    标准错误输出(stderr) 2 2> 或 2>> System.err /dev/stderr -> /proc/self/fd/2 -> /dev/pts/0
    函数返回值:
    使用return返回值:
    例子:测试nginx是否在运行 is_nginx_running.sh
    #!/bin/bash
    #
    this_pid=$$
    function is_nginx_running
    {
       ps -ef | grep nginx | grep -v $this_pid | grep -v grep > /dev/null 2>&1   
      if [ $? -eq 0 ];then
          return 0
      else
        return 1
      fi
    }
    
    is_nginx_running && echo "Nginx is running" || echo "Nginx is stopped"
                
    使用echo返回值:
    例子1:两数字相加   add.sh
    #!/bin/bash
    #
    function add
    {
        echo "`expr $1 \+ $2`"
    }
    sum=`add $1 $2`
    echo "$1 + $2 = $sum"
                
    例子2:返回Linux上所有的不可登陆用户 unlogin.sh
    #!/bin/bash
    #
    function get_users
    {
        echo `cat /etc/passwd | awk -F: '/\/sbin\/nologin/{print $1}'`
    }
    index=1
    for user in `get_users`;do
        echo "The $index user is $user"
        index=$(expr $index + 1)
    done    
    echo
    echo "System have $index users(do not login)"
    
    
    函数库:
    一个完整定义的函数库示例:
    #!/bin/echo Warning:This is a library which should not be executed,only be sourced in you scripts
    #
    function print_platform
    {
        local osname=`uname -s`
            PLATFORM=UNKNOW
            case "$osname" in
                     "FreeBSD")
                        PLATFORM="FreeBSD"
                            ;;
                        "SunOS")
                            PLATFORM="Solaris"
                            ;;
                        "Linux")
                            PLATFORM="Linux"
                            ;;
            esac
            return 0
    }
    
    function add
    {
        echo `expr $1 + $2` 
    }
    function reduce
    {
        echo `expr $1 - $2`
    }
    function multiple
    {
        echo `expr $1 \* $2`
    }
    function divide
    {
        echo `expr $1 / $2`
    }
    
    
    find命令总结:
    常用选项:
    -name 查找/etc目录下以conf结尾的文件 find /etc -name '*conf'
    -iname 查找当前目录下文件名为aa的文件,不区分大小写 find . -iname aa
    -user 查找文件属主为hdfs的所有文件 find . -user hdfs
    -group 查找文件属组为yarn的所有文件 find . -group yarn
    -type
    f 文件 find . -type f
    d 目录 find . -type d
    c 字符设备文件 find . -type c
    b 块设备文件 find . -type b
    l 链接文件 find . -type l
    p 管道文件 find . -type p
    
    -size
    -n 大小大于n的文件
    +n 大小小于n的文件
    n 大小等于n的文件
    
    例子1:查找/etc目录下小于10000字节的文件 find /etc -size -10000c
    例子2:查找/etc目录下大于1M的文件 find /etc -size +1M
    
    -mtime
    -n n天以内修改的文件
    +n n天以外修改的文件
    n 正好n天修改的文件
    
    例子1:查找/etc目录下5天之内修改且以conf结尾的文件 find /etc -mtime -5 -name '*.conf'
    例子2:查找/etc目录下10天之前修改且属主为root的文件 find /etc -mtime +10 -user root
    
    -mmin
    -n n分钟以内修改的文件
    +n n分钟以外修改的文件
    
    例子1:查找/etc目录下30分钟之前修改的文件 find /etc -mmin +30
    例子2:查找/etc目录下30分钟之内修改的目录 find /etc -mmin -30 -type d
    
    -mindepth n 表示从n级子目录开始搜索
    例子:在/etc下的3级子目录开始搜索 find /etc -mindepth 3
    
    -maxdepth n 表示最多搜索到n-1级子目录
    
    例子1:在/etc下搜索符合条件的文件,但最多搜索到2级子目录 find /etc -maxdepth 3 -name '*.conf'
    例子2:
    find ./etc/ -type f -name '*.conf' -size +10k -maxdepth 2
    
    了解选项:
    -nouser 查找没有属主的用户
    例子:find . -type f -nouser
    -nogroup 查找没有属组的用户
    例子:find . -type f -nogroup
    -perm
    例子:find . -perm 664
    -prune
    通常和-path一起使用,用于将特定目录排除在搜索条件之外
    例子1:查找当前目录下所有普通文件,但排除test目录
    find . -path ./etc -prune -o -type f
    例子2:查找当前目录下所有普通文件,但排除etc和opt目录
    find . -path ./etc -prune -o -path ./opt -prune -o -type f
    例子3:查找当前目录下所有普通文件,但排除etc和opt目录,但属主为hdfs
    find . -path ./etc -prune -o -path ./opt -prune -o -type f -a -user hdfs
    例子4:查找当前目录下所有普通文件,但排除etc和opt目录,但属主为hdfs,且文件大小必须大于500字节
    find . -path ./etc -prune -o -path ./opt -prune -o -type f -a -user hdfs -a -size +500c
    
    -newer file1
    例子:find /etc -newer a
    操作:
    -prin       打印输出
    -exec       对搜索到的文件执行特定的操作,格式为-exec 'command' {} \;
    例子1:搜索/etc下的文件(非目录),文件名以conf结尾,且大于10k,然后将其删除
       find ./etc/ -type f -name '*.conf' -size +10k -exec rm -f {} \;
    例子2:将/var/log/目录下以log结尾的文件,且更改时间在7天以上的删除
            find /var/log/ -name '*.log' -mtime +7 -exec rm -rf {} \;
    例子3:搜索条件和例子1一样,只是不删除,而是将其复制到/root/conf目录下
            find ./etc/ -size +10k -type f -name '*.conf' -exec cp {} /root/conf/ \;
    -ok和exec功能一样,只是每次操作都会给用户提示
    
    逻辑运算符:
    -a          与
    -o          或
    -not|!      非
    
    例子1:查找当前目录下,属主不是hdfs的所有文件
    find . -not -user hdfs | find . ! -user hdfs
    
    例子2:查找当前目录下,属主属于hdfs,且大小大于300字节的文件
    find . -type f -a -user hdfs -a -size +300c
    
    例子3:查找当前目录下的属主为hdfs或者以conf结尾的普通文件
    find . -type f -a -user hdfs -o -name '*.conf'
    
    观察find . -type f -a -user hdfs -o -name '*.conf' -exec ls -rlt {} \;
    find . -type f -a \( -user hdfs -o -name '*.conf' \) -exec ls -rlt {} \;
    
    
    sed 修改用法总结:
    1、1s/old/new/
    2、5,10s/old/new/
    3、10,+10s/old/new/
    4、/pattern1/s/old/new/
    5、/pattern1/,/pattern2/s/old/new/
    6、/pattern1/,20s/old/new/
    7、15,/pattern1/s/old/new/
    
    练习例子:
    1、修改/etc/passwd中第1行中第1个root为ROOT
    sed -i '1s/root/ROOT/' passwd
    2、修改/etc/passwd中第5行到第10行中所有的/sbin/nologin为/bin/bash
    sed -i '5,10s/\/sbin\/nologin/\/bin\/bash/g' passwd
    3、修改/etc/passwd中匹配到/sbin/nologin的行,将匹配到行中的login改为大写的LOGIN
    sed -i '/\/sbin\/nologin/s/login/LOGIN/g' passwd
    4、修改/etc/passwd中从匹配到以root开头的行,到匹配到行中包含mail的所有行。修改内为将这些所有匹配到的行中的bin改为HADOOP
    sed -i '/^root/,/mail/s/bin/HADOOP/g' passwd
    5、修改/etc/passwd中从匹配到以root开头的行,到第15行中的所有行,修改内容为将这些行中的nologin修改为SPARK
    sed -i '/^root/,15s/nologin/SPARK/g' passwd
    6、修改/etc/passwd中从第15行开始,到匹配到以yarn开头的所有航,修改内容为将这些行中的bin换位BIN
    sed -i '15,/^yarn/s/bin/BIN/g' passwd
    
    追加用法总结:
    1、a 在匹配行后面追加
    2、i 在匹配行前面追加
    3、r 将文件内容追加到匹配行后面
    4、w 将匹配行写入指定文件
    
    追加用法示例详解:
    1、a append
    (1)、passwd文件第10行后面追加"Add Line Behind"
        sed -i '10a Add Line Begind' passwd
    (2)、passwd文件第10行到第20行,每一行后面都追加"Test Line Behind"
        sed -i '10,20a Test Line Behind' passwd
    (3)、passwd文件匹配到/bin/bash的行后面追加"Insert Line For /bin/bash Behind"
        sed -i '/\/bin\/bash/a Insert Line For /bin/bash Behind' passwd
            
    2、i
    (1)、passwd文件匹配到以yarn开头的行,在匹配航前面追加"Add Line Before"
        sed -i '/^yarn/i Add Line Before' passwd
    (2)、passwd文件每一行前面都追加"Insert Line Before Every Line"
        sed -i 'i Insert Line Before Every Line' passwd
    3、r
    (1)、将/etc/fstab文件的内容追加到passwd文件的第20行后面
        sed -i '20r /etc/fstab' passwd
    (2)、将/etc/inittab文件内容追加到passwd文件匹配/bin/bash行的后面
        sed -i '/\/bin\/bash/r /etc/inittab' passwd
    (3)、将/etc/vconsole.conf文件内容追加到passwd文件中特定行后面,匹配以ftp开头的行,到第18行的所有行
        sed -i '//,18r /etc/vconsole.conf' passwd
    
    4、w
    (1)、将passwd文件匹配到/bin/bash的行追加到/tmp/sed.txt文件中
        sed -i '/\/bin\/bash/w /tmp/sed.txt' passwd
    (2)、将passwd文件从第10行开始,到匹配到hdfs开头的所有行内容追加到/tmp/sed-1.txt
        sed -i '10,/^hdfs/w /tmp/sed-1.txt' passwd
    
    删除用法总结:
    1、1d
    2、5,10d
    3、10,+10d
    4、/pattern1/d
    5、/pattern1/,/pattern2/d
    6、/pattern1/,20d
    7、15,/pattern1/d
        
    练习例子:
    1、删除/etc/passwd中的第15行
      sed -i '15d' /etc/passwd
    2、删除/etc/passwd中的第8行到第14行的所有内容
       sed -i '8,14d' passwd
    3、删除/etc/passwd中的不能登录的用户(筛选条件:/sbin/nologin)
      sed -i '/\/sbin\/nologin/d' passwd
    4、删除/etc/passwd中以mail开头的行,到以yarn开头的行的所有内容
      sed -i '/^mail/,/^yarn/d' passwd
    5、删除/etc/passwd中第一个不能登录的用户,到第13行的所有内容
      sed -i '/\/sbin\/nologin/,13d' passwd
    6、删除/etc/passwd中第5行到以ftp开头的所有行的内容
       sed -i '5,/^ftp/d' passwd
    7、删除/etc/passwd中以yarn开头的行到最后行的所有内容
       sed -i '/^yarn/,$d' passwd
    
    典型需求:
    1、删除配置文件中的所有注释行和空行
       sed -i '/[:blank:]*#/d;/^$/d' nginx.conf
    2、在配置文件中所有不以#开头的行前面添加*符号,注意:以#开头的行不添加
       sed -i 's/^[^#]/\*&/g' nginx.conf
    
    
    #!/bin/bash
    FILE_NAME=/root/my.cnf
    function get_all_segments
    {
        echo "`sed -n '/\[.*\]/p' $FILE_NAME  | sed -e 's/\[//g' -e 's/\]//g'`"
    }
    
    function count_items_in_segment
    {
        items=`sed -n '/\['$1'\]/,/\[.*\]/p' $FILE_NAME | grep -v "^#" | grep -v "^$" | grep -v "\[.*\]"`
        index=0
        for item in $items
        do
            index=`expr $index + 1`
        done
        echo $index
    }
    
    number=0
    for segment in `get_all_segments`
    do
        number=`expr $number + 1`
        items_count=`count_items_in_segment $segment`
        echo "$number: $segment  $items_count"
    done
    
    
    my.cnf:
    # this is read by the standalone daemon and embedded servers
    [client]
    port=3306
    socket=/tmp/mysql.socket
    
    #ThisSegmentForserver
    [server]
    innodb_buffer_pool_size=91750M
    innodb_buffer_pool_instances=8
    innodb_buffer_pool_load_at_startup=1
    innodb_buffer_pool_dump_at_shutdown=1
    innodb_data_file_path=ibdata1:1G:autoextend
    innodb_flush_log_at_trx_commit=1
    innodb_log_buffer_size=32M
    innodb_log_file_size=2G
    innodb_log_files_in_group=2
    innodb_max_undo_log_size=4G
    innodb_undo_directory=undolog
    innodb_undo_tablespaces=95
    
    #thisisonlyforthemysqldstandalonedaemon
    [mysqld]
    port=3306
    socket=/tmp/mysql.sock
    basedir=/usr/local/mysql
    datadir=/data/mysql
    pid-file=/data/mysql/mysql.pid
    user=mysql
    bind-address=0.0.0.0
    sort_buffer_size=16M
    join_buffer_size=16M
    thread_cache_size=3000
    interactive_timeout=600
    wait_timeout=600
    
    #ThisSegmentFormysqld_safe
    [mysqld_safe]
    log-error=/var/log/mariadb/mariadb.log
    pid-file=/var/run/mariadb/mariadb.pid
    max_connections=1000
    open_files_limit=65535
    thread_stack=512K
    external-locking=FALSE
    max_allowed_packet=32M
    
    #thisisonlyforembeddedserver
    [embedded]
    gtid_mode=on
    enforce_gtid_consistency=1
    log_slave_updates
    slave-rows-search-algorithms='INDEX_SCAN,HASH_SCAN'
    binlog_format=row
    binlog_checksum=1
    relay_log_recovery=1
    relay-log-purge=1
    
    #usethisgroupforoptionsthatolderserversdon'tunderstand
    [mysqld-5.5]
    key_buffer_size=32M
    read_buffer_size=8M
    read_rnd_buffer_size=16M
    bulk_insert_buffer_size=64M
    myisam_sort_buffer_size=128M
    myisam_max_sort_file_size=10G
    myisam_repair_threads=1
    lock_wait_timeout=3600
    explicit_defaults_for_timestamp=1
    innodb_file_per_table=1
    
    awk
    总结,内置变量:
    $0:打印行所有信息
    $1~$n:打印行的第1到n个字段的信息
    NF:Number Field 处理行的字段个数
    NR:Number Row 处理行的行号
    FNR:File Number Row 多文件处理时,每个文件单独记录行号
    FS:Field Separator 字段分割符,不指定时默认以空格或tab键分割
    RS:Row Separator 行分隔符,不指定时以回车分割\n
    OFS :Output Filed Separator 输出字段分隔符。
    ORS:Output Row Separator 输出行分隔符
    FILENAME 处理文件的文件名
    ARGC :命令行参数个数
    ARGV:命令行参数数组
    
    awk格式化输出之printf总结:
    格式符
    %s 打印字符串
    %d 打印10进制数
    %f 打印浮点数
    %x 打印16进制数
    %o 打印8进制数
    %e 打印数字的科学计数法格式
    %c 打印单个字符的ASCII码
    
    修饰符
    - 左对齐
    + 右对齐
    #显示8进制在前面加0,显示16进制在前面加0x
    
    格式符示例:
    1、以字符串格式打印/etc/passwd中的第7个字段,以":"作为分隔符
    awk 'BEGIN{FS=":"} {printf "%s",$7}' /etc/passwd
    
    2、以10进制格式打印/etc/passwd中的第3个字段,以":"作为分隔符
    awk 'BEGIN{FS=":"} {printf "%d\n",$3}' /etc/passwd
    
    3、以浮点数格式打印/etc/passwd中的第3个字段,以":"作为分隔符
    awk 'BEGIN{FS=":"} {printf "%0.3f\n",$3}' /etc/passwd
    
    4、以16进制数格式打印/etc/passwd中的第3个字段,以":"作为分隔符
    awk 'BEGIN{FS=":"} {printf "%#x\n",$3}' /etc/passwd
    
    5、以8进制数格式打印/etc/passwd中的第3个字段,以":"作为分隔符
    awk 'BEGIN{FS=":"} {printf "%#o\n",$3}' /etc/passwd
    
    6、以科学计数法格式打印/etc/passwd中的第3个字段,以":"作为分隔符
    awk 'BEGIN{FS=":"} {printf "%e\n",$3}' /etc/passwd
    修饰符示例:
    1、左对齐格式
    2、右对齐格式
    3、打印8进制或16进制数字是在前面加#
    
    awk模式匹配用法总结:
    第一种方法:RegExp
    第二种方法:运算符匹配
    1、RegExp
    匹配/etc/passwd文件行中含有root字符串的所有行
    awk 'BEGIN{FS=":"}/root/{print $0}' /etc/passwd
    匹配/etc/passwd文件行中以yarn开头的所有行
    awk 'BEGIN{FS=":"}/^yarn/{print $0}' /etc/passwd
        
    2、运算符匹配
    关系运算符匹配:
        <           小于
        >           大于
        <=          小于等于
        >=          大于等于
        ==          等于
        !=          不等于
        ~           匹配正则表达式
        !~          不匹配正则表达式        
    (1)、以:为分隔符,匹配/etc/passwd文件中第3个字段小于50的所有行信息
    awk 'BEGIN{FS=":"}$3<50{print $0}' /etc/passwd
    (2)、以:为分隔符,匹配/etc/passwd文件中第3个字段大于50的所有行信息
    awk 'BEGIN{FS=":"}$3>50{print $0}' /etc/passwd
    (3)、以:为分隔符,匹配/etc/passwd文件中第7个字段为/bin/bash的所有行信息
    awk 'BEGIN{FS=":"}$7=="/bin/bash"{print $0}' /etc/passwd
    (4)、以:为分隔符,匹配/etc/passwd文件中第7个字段不为/bin/bash的所有行信息
    awk 'BEGIN{FS=":"}$7!="/bin/bash"{print $0}' /etc/passwd
    (5)、以:为分隔符,匹配/etc/passwd中第3个字段包含3个以上数字的所有行信息
    awk 'BEGIN{FS=":"}$3~/[0-9]{3,}/{print $0}' /etc/passwd
            
    布尔运算符匹配:
    ||          或
    &&          与
    !           非
                
    (1)、以:为分隔符,匹配/etc/passwd文件中包含hdfs或yarn的所有行信息
    awk 'BEGIN{FS=":"}$1=="hdfs" || $1=="yarn" {print $0}' /etc/passwd
    (2)、以:为分隔符,匹配/etc/passwd文件中第3个字段小于50并且第4个字段大于50的所有行信息
    awk 'BEGIN{FS=":"}$3<50 && $4>50 {print $0}' /etc/passwd
    
    awk动作中的表达式用法总结:
    算数运算符
    + 加
    - 减
    * 乘
    / 除
    % 取模
    ^或** 乘方
    ++x 在返回x变量之前,x变量加1
    x++ 在返回x变量之后,x变量加1
    --x 在返回x变量之前,x变量减1
    x-- 在返回x变量之后,x变量减1
    
    1、使用awk计算/etc/services中的空白行数量
    awk '/^$/{sum++}END{print sum}' /etc/services
    2、计算学生课程分数平均值,学生课程文件内容如下:
    
    Allen 80 90 96 98
    Mike 93 98 92 91
    Zhang 78 76 87 92
    Jerry 86 89 68 92
    Han 85 95 75 90
    Li 78 88 98 100
    awk 'BEGIN{printf "%-8s%-8s%-8s%-8s%-8s%s\n","Name","Yuwen","Math","English","Pysical","Average"}{total=$2+$3+$4+$5;AVG=total/4;printf "%-8s%-8d%-8d%-8d%-8d%0.2f\n",$1,$2,3,$4,$5,AVG}' student.txt
    
    3、使用awk输出/etc/passwd文件的行数。分两种方式显示行数,一种是正序如1.2.3.4...,另一种是倒序如...5.4.3.2.1
    
    awk中的字符串函数
    length(str)             计算长度
    index(str1,str2)            返回在str1中查询到的str2的位置
    tolower(str)                小写转换
    toupper(str)                大写转换    
    split(str,arr,fs)               分隔字符串,并保存到数组中
    match(str,RE)               返回正则表达式匹配到的子串的位置
    substr(str,m,n)             截取子串,从m个字符开始,截取n位。n若不指定,则默认截取到字符串尾
    sub(RE,RepStr,str)          替换查找到的第一个子串
    gsub(RE,RepStr,str)     替换查找到的所有子串
        
    1、以:为分隔符,返回/etc/passwd中每行中每个字段的长度   
    root:x:0:0:root:/root:/bin/bash
    4:1:1:1:4:5:9
    代码:
    BEGIN{
            FS=":"
    }
    {
        i=1
        while(i<=NF)
        {
        if(i==NF)
            printf "%d",length($i)
        else
            printf "%d:",length($i)
        i++
        }
        print ""
    }
    2、搜索字符串"I have a dream"中出现"ea"子串的位置 
    (1)、awk 'BEGIN{str="I hava a dream";location=index(str,"ea");print location}'
    (2)、awk 'BEGIN{str="I hava a dream";location=match(str,"ea");print location}'
    3、将字符串"Hadoop is a bigdata Framawork"全部转换为小写
    awk 'BEGIN{str="Hadoop is a bigdata Framework";print tolower(str)}'
            
    4、将字符串"Hadoop is a bigdata Framawork"全部转换为大写
    awk 'BEGIN{str="Hadoop is a bigdata Framework";print toupper(str)}'
            
    5、将字符串"Hadoop Kafka Spark Storm HDFS YARN Zookeeper",按照空格为分隔符,分隔每部分保存到数组array中
    awk 'BEGIN{str="Hadoop Kafka Spark Storm HDFS YARN Zookeeper";split(str,arr);for(a in arr) print arr[a]}'
        
    6、搜索字符串"Tranction 2345 Start:Select * from master"第一个数字出现的位置
    awk 'BEGIN{str="Tranction 2345 Start:Select * from master";location=match(str,/[0-9]/);print location}'
        
    7、截取字符串"transaction start"的子串,截取条件从第4个字符开始,截取5位
    awk 'BEGIN{str="transaction start";print substr(str,4,5)}'
    awk 'BEGIN{str="transaction start";print substr(str,4)}'
            
    8、替换字符串"Tranction 243 Start,Event ID:9002"中第一个匹配到的数字串为$符号
    awk 'BEGIN{str="Tranction 243 Start,Event ID:9002";count=sub(/[0-9]+/,"$",str);print count,str}'
    awk 'BEGIN{str="Tranction 243 Start,Event ID:9002";count=gsub(/[0-9]+/,"$",str);print count,str}'
        
    awk中常用选项
    -v 定义或引用变量
    -f 指定awk命令文件
    -F 指定分隔符
    -V 查看awk的版本号
    
    Shell中数组的用法:
    array=("Allen" "Mike" "Messi" "Jerry" "Hanmeimei" "Wang")
        
    打印元素:       echo ${array[2]}
    打印元素个数:     echo ${#array[@]}
    打印元素长度: echo ${#array[3]}
    给元素赋值:      array[3]="Li"
    删除元素:       unset array[2];unset array
    分片访问:       echo ${array[@]:1:3}
    元素内容替换: ${array[@]/e/E} 
    只替换第一个e;${array[@]//e/E}    替换所有的e
    数组的遍历:
    for a in ${array[@]}
    do
        echo $a
    done
    
    awk中数组的用法:
    在awk中,使用数组时,不仅可以使用1.2..n作为数组下标,也可以使用字符串作为数组下标
    当使用1.2.3..n时,直接使用array[2]访问元素;需要遍历数组时,使用以下形式:
    str="Allen Jerry Mike Tracy Jordan Kobe Garnet"
    split(str,array)
    for(i=1;i<=length(array);i++)
        print array[i]
    当使用字符串作为数组下标时,需要使用array[str]形式访问元素;遍历数组时,使用以下形式:
    array["var1"]="Jin"
    array["var2"]="Hao"
    array["var3"]="Fang"
    for(a in array)
        print array[a]
                
    典型常用例子:
    1、统计主机上所有的TCP连接状态数,按照每个TCP状态分类
    netstat -an | grep tcp | awk '{array[$6]++}END{for(a in array) print a,array[a]}'
                
    2、计算横向数据总和,计算纵向数据总和
    allen   80  90  87  91  348
    mike    78  86  93  96  256
    Kobe    66  92  82  78  232
    Jerry   98  74  66  54  356
    Wang    87  21  100 43  322
           234  342   451 456 342
                
    BEGIN {
        printf "%-10s%-10s%-10s%-10s%-10s%-10s\n","Name","Yuwen","Math","English","Physical","Total"
    }
    {
        total=$2+$3+$4+$5
        yuwen_sum+=$2
        math_sum+=$3
        eng_sum+=$4
        phy_sum+=$5
        printf "%-10s%-10d%-10d%-10d%-10d%-10d\n",$1,$2,$3,$4,$5,total
    }
    END {
      printf "%-10s%-10d%-10d%-10d%-10d\n","",yuwen_sum,math_sum,eng_sum,phy_sum
    }   
    
    

    相关文章

      网友评论

          本文标题:source code for shell

          本文链接:https://www.haomeiwen.com/subject/tkahwdtx.html