How to remove the last character from a bash grep output

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

    In Bash using only one external utility:

    IFS='= ' read -r discard COMPANY_NAME <<< $(grep "company_name" file.txt)
    COMPANY_NAME=${COMPANY_NAME/%?}
    
    0 讨论(0)
  • 2020-12-08 06:53

    Assuming the quotation marks are actually part of the output, couldn't you just use the -o switch to return everything between the quote marks?

    COMPANY_NAME="\"ABC Inc\";" | echo $COMPANY_NAME | grep -o "\"*.*\""
    
    0 讨论(0)
  • 2020-12-08 06:54

    don't have to chain so many tools. Just one awk command does the job

     COMPANY_NAME=$(awk -F"=" '/company_name/{gsub(/;$/,"",$2) ;print $2}' file.txt)
    
    0 讨论(0)
  • 2020-12-08 06:56

    I am not finding that sed 's/;$//' works. It doesn't trim anything, though I'm wondering whether it's because the character I'm trying to trim off happens to be a "$". What does work for me is sed 's/.\{1\}$//'.

    0 讨论(0)
  • 2020-12-08 06:58

    Some refinements to answer above. To remove more than one char you add multiple question marks. For example, to remove last two chars from variable $SRC_IP_MSG, you can use:

    SRC_IP_MSG=${SRC_IP_MSG%??}
    
    0 讨论(0)
  • 2020-12-08 06:59

    Using sed, if you don't know what the last character actually is:

    $ grep company_name file.txt | cut -d '=' -f2 | sed 's/.$//'
    "Abc Inc"
    
    0 讨论(0)
提交回复
热议问题