rkpt
rkpt

Reputation: 39

Print a part of string regex bash

From this content (in a file):

myspecificBhost.fqdn.com myspecificaBhost.fqdn.com myspecificzBhost.fqdn.com

I need to print the next 4 characters from the "B":

Bhost

I tried:

echo ${var:position1:lenght}

but position 1 is never equal

Upvotes: 1

Views: 125

Answers (4)

MLSC
MLSC

Reputation: 5972

try sed command:

sed -nr '/.*c(.{4,6}).*/s//\1/p' input.txt | cut -c2-6
RESULT:
Bhost

With grep command:

cat input.txt | grep -o B.... | head -1
RESULT:
Bhost

Upvotes: 1

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17198

Bash using parameter substitution. Outputs the 4 characters after the first 'B':

text='myspecificBhost.fqdn.com myspecificaBhost.fqdn.com myspecificzBhost.fqdn.com'

text=${text#*B}
text=${text:0:4}
echo "${text}"

Output:

host

To get the leading 'B' use

echo "B${text}"

Upvotes: 0

anubhava
anubhava

Reputation: 785306

Using BASH regex:

s='myspecificBhost.fqdn.com myspecificaBhost.fqdn.com myspecificzBhost.fqdn.com'
[[ "$s" =~ (B[a-z][a-z][a-z][a-z]) ]] && echo "${BASH_REMATCH[1]}"
Bhost

Upvotes: 2

drolando
drolando

Reputation: 507

Try with:

cat file | grep -o B....

Upvotes: 0

Related Questions