Home > Back-end >  Get char before Substring in bash
Get char before Substring in bash

Time:04-12

i try to get the char before a substring in bash. Some examples of the String:

label="LLL:EXT:xxx/Resources/Private/Language/locallang.xlf:flux.content"

or:

label='LLL:EXT:xxx/Resources/Private/Language/locallang.xlf:flux.content'

or:

$this->getLanguageService()->sL('LLL:EXT:xxx/Resources/Private/Language/locallang.xlf:flux.content'

i need to know if there is a single- or doublequote before the LLL. :)

CodePudding user response:

You can get the character using pure Bash code with:

[[ $string =~ (.)LLL ]] && char=${BASH_REMATCH[1]}

See the sections on [[...]] and BASH_REMATCH in the Bash Reference Manual.

CodePudding user response:

You can use grep for this.

grep -E -o '.{0,1}LLL' file
grep -E -o '.{0,1}LLL' file | cut -c-1 # shows only the first character
  • -E indicates the pattern is an extended regular expression
  • -o shows only the matching portion
  • '.{0,1}LLL' specifies the pattern with the first preceding character appended

CodePudding user response:

You are asking whether or not there is a ' or " before LLL. The shortest answer would be grep -q "['\"]LLL".

If the exit code is 0, then the answer is yes, if the exit code is 1, then the answer is no.

For example:

$ echo 'label="LLL:EXT:xxx/Resources/Private/Language/locallang.xlf:flux.content"' | grep -q "['\"]LLL"
$ echo $?
0
$ echo test | grep -q "['\"]LLL"
$ echo $?
1
  •  Tags:  
  • bash
  • Related