How to remove the last character from a bash grep output

后端 未结 14 1566
爱一瞬间的悲伤
爱一瞬间的悲伤 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:45

    I'd use head --bytes -1, or head -c-1 for short.

    COMPANY_NAME=`cat file.txt | grep "company_name" | cut -d '=' -f 2 | head --bytes -1`
    

    head outputs only the beginning of a stream or file. Typically it counts lines, but it can be made to count characters/bytes instead. head --bytes 10 will output the first ten characters, but head --bytes -10 will output everything except the last ten.

    NB: you may have issues if the final character is multi-byte, but a semi-colon isn't

    I'd recommend this solution over sed or cut because

    • It's exactly what head was designed to do, thus less command-line options and an easier-to-read command
    • It saves you having to think about regular expressions, which are cool/powerful but often overkill
    • It saves your machine having to think about regular expressions, so will be imperceptibly faster

提交回复
热议问题