0

I'm trying to check if some string from length 1 and has only following chars: [RGWBO].

I'm trying the following but it doesn't work, what am I missing?

if [[ !(${line[4]} =~ [RGWBO]) ]];
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
triple fault
  • 13,410
  • 8
  • 32
  • 45

4 Answers4

2

This is what you want:

if [[ ${line[4]} =~ ^[RGWBO]+$ ]];

This means that the string right from the start till the end must have [RGWBO] characters one or more times.

If you want to negate the expression just use ! in front of [[ ]]:

if ! [[ ${line[4]} =~ ^[RGWBO]+$ ]];

Or

if [[ ! ${line[4]} =~ ^[RGWBO]+$ ]];
Aleks-Daniel Jakimenko-A.
  • 10,335
  • 3
  • 41
  • 39
1

This one would work with any usable version of Bash:

[[ -n ${LINE[0]} && ${LINE[0]} != *[^RGWB0]* ]]

Even though I prefer the simplicity of extended globs:

shopt -s extglob
[[ ${LINE[0]} == +([RGWBO]) ]]
konsolebox
  • 72,135
  • 12
  • 99
  • 105
0

Approach

  1. Test the string length with ${#myString}, if it's egal to 1 proceed to step 2 ;
  2. Does is contains your pattern.

Code

re='[RGWBO]'; 
while read -r line; do
  if (( ${#line} == 1 )) && [[ $line == $re ]]; then
    echo "yes: $line"
  else 
    echo "no: $line" 
  fi
done < test.txt

Resources

You may want to look at the following links:

Data

The test.txt file contains this

RGWBO
RGWB
RGW
RG
R
G
W
B
O
V
Community
  • 1
  • 1
Édouard Lopez
  • 40,270
  • 28
  • 126
  • 178
0

Use expr (expression evaluator) to do substring matching.

#!/bin/bash
pattern='[R|G|W|B|O]'
string=line[4]
res=`expr match "$string" $pattern`

if [ "${res}" -eq "1" ]; then
  echo 'match'
else
  echo 'doesnt match'
fi
P̲̳x͓L̳
  • 3,615
  • 3
  • 29
  • 37