Home > Software engineering >  How to remove first & last character in bash string
How to remove first & last character in bash string

Time:09-01

#!/bin/bash

MA=$(bt-device -l | cut -d " " -f 3)
MAC=${MA:1: -1}
bluetoothctl connect $MAC

Expected Result

98:9E:63:18:00:88

Actual result

(98:9E:63:18:00:88

CodePudding user response:

Using sed it can be done in a single step:

s='Denny’s Tunez (98:9E:63:18:00:88)'
echo "$s" | sed -E 's/.* \(|)//g'

98:9E:63:18:00:88

So for your example you can use:

mac=$(bt-device -l | sed -E 's/.* \(|)//g')

CodePudding user response:

A few alternatives:

$ echo 'Denny’s Tunez (98:9E:63:18:00:88)' | sed -En 's/^[^(]*\(([^)]*)\).*/\1/p'
98:9E:63:18:00:88

$ echo 'Denny’s Tunez (98:9E:63:18:00:88)' | cut -d'(' -f2 | cut -d')' -f1
98:9E:63:18:00:88

$ echo 'Denny’s Tunez (98:9E:63:18:00:88)' | awk -F'[)(]' '{print $2}'
98:9E:63:18:00:88

$ echo 'Denny’s Tunez (98:9E:63:18:00:88)' | grep -Eow '(..)(:..){5}'
98:9E:63:18:00:88

$ x='Denny’s Tunez (98:9E:63:18:00:88)'
$ y="${x//*\(/}"
$ y="${y//\)*}"
$ echo $y
98:9E:63:18:00:88

CodePudding user response:

With GNU bash and its Parameter Expansion:

s="(98:9E:63:18:00:88)"

s="${s/#?/}"  # remove first character
s="${s/%?/}"  # remove last character

echo "$s"

Output:

98:9E:63:18:00:88

CodePudding user response:

You can use parameter expansion:

  1. offset and length
echo ${MA:1: -1}
  1. prefix and suffix removal
tmp=${MA#(}
echo ${tmp%)}
  1. parameter matching
tmp=${MA/#\(}
echo ${tmp/%\)}

Another approach is to:

  1. whitelist what you do want
echo "$MA" | tr -dC '[0-9A-F:]'
  •  Tags:  
  • bash
  • Related