How to remove the last character from a bash grep output

后端 未结 14 1584
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 06:29
COMPANY_NAME=`cat file.txt | grep \"company_name\" | cut -d \'=\' -f 2` 

outputs something like this

\"Abc Inc\";

14条回答
  •  醉酒成梦
    2020-12-08 06:41

    I believe the cleanest way to strip a single character from a string with bash is:

    echo ${COMPANY_NAME:: -1}
    

    but I haven't been able to embed the grep piece within the curly braces, so your particular task becomes a two-liner:

    COMPANY_NAME=$(grep "company_name" file.txt); COMPANY_NAME=${COMPANY_NAME:: -1} 
    

    This will strip any character, semicolon or not, but can get rid of the semicolon specifically, too. To remove ALL semicolons, wherever they may fall:

    echo ${COMPANY_NAME/;/}
    

    To remove only a semicolon at the end:

    echo ${COMPANY_NAME%;}
    

    Or, to remove multiple semicolons from the end:

    echo ${COMPANY_NAME%%;}
    

    For great detail and more on this approach, The Linux Documentation Project covers a lot of ground at http://tldp.org/LDP/abs/html/string-manipulation.html

提交回复
热议问题