linux shell之字符串的更具字符分割和刪除字符和文本內(nèi)容的刪除以及內(nèi)容是否匹配成功

1  字符串的更具字符分割

1) xargs分割

    echo "chenyu*hello*word" | xargs -d "*"
    chenyu hello word

2) awk分割

    echo "chenyu*hello*word" | awk -F "*" '{print $1}'
    chenyu

 
2 字符串的刪除字符

1)用tr命令

    echo "chenyu ni hao ya" | tr -d 'y'
    chenu ni hao a

2)用sed命令

    echo  "hello*word*word" | sed 's/*//g'
    hellowordword

 
3 文本內(nèi)容的刪除

用sed命令

    cat 1.txt
    chenyu
    nihao
    hello
    word
    chenyu
    nihao
    dongma
    sed -i '/chenyu/d' 1.txt
    cat 1.txt
    nihao
    hello
    word
    nihao
    dongma


4 grep -q 用于if邏輯判斷

-q 參數(shù),本意是 Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected.  中文意思為,安靜模式,不打印任何標(biāo)準(zhǔn)輸出。如果有匹配的內(nèi)容則立即返回狀態(tài)值0

自己測試如下

    #/bin/bash
     
    value="chenyu ni hao ya"
     
    #匹配成功執(zhí)行$?返回0
    echo "hello" | grep -q "he";
    echo $?
    #匹配失敗執(zhí)行$?非0
    echo "hello" | grep -q "hehelodaf";
    echo $?
     
    #如果能匹配成功那么就到then反之到else
    if echo $value | grep -q "chenyuddsa";
    then
       echo "first success"
    else
       echo "first fail"
    fi
     
     
    if echo $value | grep -q "hao";
    then
       echo "second success"
    else
       echo "second fail"
    fi

允許結(jié)果如下:

    ./grep.sh
    0
    1
    first fail
    second success


 
5 grep -i(忽略大小寫)來判斷結(jié)果

    #/bin/bash
     
    value="chenyu"
    echo $value | grep -i "chen" > /dev/null
     
    if [ $? -eq 0 ];
    then
        echo "grep success"
    else
        echo "grep fail"
    fi
     
    echo $value | grep -i "chengongyu" > /dev/null
     
    if [ $? -eq 0 ];
    then
        echo "grep success"
    else
        echo "grep fail"
    fi
        

運(yùn)行結(jié)果

    grep success
    grep fail



 
作者:chen.yu
深信服三年半工作經(jīng)驗(yàn),目前就職游戲廠商,希望能和大家交流和學(xué)習(xí),
微信公眾號(hào):編程入門到禿頭 或掃描下面二維碼
零基礎(chǔ)入門進(jìn)階人工智能(鏈接)