Pelicanux

Just A Few Random Words

Bash: Strings Handling

Use of regex with bash

1
2
3
4
5
6
7
8
9
10
string="rob-espierre:V9_NOE"

if [[ $string =~ (^[a-z\-]*):([a-zA-Z0-9_]*) ]]; then
  host=${BASH_REMATCH[1]}
  schema=${BASH_REMATCH[2]}
  echo $host
  echo $schema
else
  echo "No match found"
fi

Case

1
2
3
4
5
6
7
# min to MAJ
a=toto
echo ${a^^*}

# MAJ to min
a=TOTO
echo${a,,*}

Handling filenames

Examples below are inspired from bash manual pages, looking for parameter expansion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Remove last extension
x="/foo/fizzbuzz.bar.quux"
y=${x%.*}
echo $y
  --> /foo/fizzbuzz.bar

# Remove everything after the first dot
y=${x%%.*}
echo $y
  --> /foo/fizzbuzz

# Get raw filename
x="/foo/fizzbuzz.bar"
y=${x%.bar}
echo ${y##*/}
  --> fizzbuzz

# Change extension
x="/foo/fizzbuzz.bar"
y=${x/bar/txt}
echo $y
  --> /foo/fizzbuzz.txt