Sopalajo de Arrierez
Sopalajo de Arrierez

Reputation: 3850

Linux shell: How can I remove leading/trailing characters before/after specific characters inside a string?

Case scenario:

$ var="This is my ___ va__riable ___for___ num_ber ___45___"
$ echo $var
This is my ___ va__riable ___for___ the num_ber ___45___

I would like var to be transformed so that ___N___ (3 leading _, any number, and 3 trailing _) will become just N, this is: just leave the number.

So the resulting var should be:

This is my ___ va__riable ___for___ the num_ber 45

Note that only 3 consecutive _ surrounding a number are removed. The rest are left.

How could I do this?

My (weak) approach:

echo $var | sed 's/___[0-9]___/[0-9]/'

(I was thinking about some way for sed to replace the number with the same number, but I don't know if this can be done with sed).

Upvotes: 0

Views: 1877

Answers (1)

William Pursell
William Pursell

Reputation: 212228

$ echo "$var" | sed 's/___\([0-9][0-9]*\)___/\1/g'

You can also use extended regexes:

$ echo "$var" | sed -E 's/___([0-9]+)___/\1/g'

Upvotes: 3

Related Questions