5

I am trying to get from user a path as an input.
The user will enter a specific path for specific application:

script.sh /var/log/dbhome_1/md5

I've wanted to convert the number of directory (in that case - 1) to * (asterisk). later on, the script will do some logic on this path.

When i'm trying sed on the input, i'm stuck with the number -

echo "/var/log/dbhome_1/md5" | sed "s/dbhome_*/dbhome_\*/g"

and the input will be -

/var/log/dbhome_*1/md5

I know that i have some problems with the asterisk wildcard and as a char... maybe regex will help here?

Sagi
  • 75
  • 1
  • 5

3 Answers3

3

Code for GNU :

sed "s#1/#\*/#"

.

$echo "/var/log/dbhome_1/md5" | sed "s#1/#\*/#"
"/var/log/dbhome_*/md5"

Or more general:

sed "s#[0-9]\+/#\*/#"

.

$echo "/var/log/dbhome_1234567890/md5" | sed "s#[0-9]\+/#\*/#"
"/var/log/dbhome_*/md5"
captcha
  • 3,756
  • 12
  • 21
2

use this instead:

echo "/var/log/dbhome_1/md5" | sed "s/dbhome_[0-9]\+/dbhome_\*/g"

[0-9] is a character class that contains all digits

Thus [0-9]\+ matches one or more digits

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
0

If your script is in (which I assume when I see the tag, but I also doubt it when I see its name script.sh which seems to have the wrong extension for a script), you might as well use pure stuff: /var/log/dbhome_1/md5 will very likely be in positional parameter $1, and what you want will be achieved by:

echo "${1//dbhome_+([[:digit:]])/dbhome_*}"

If this seems to fail, it's probably because your extglob shell optional behavior is turned off. In this case, just turn it on with

shopt -s extglob

Demo:

$ shopt -s extglob
$ a=/var/log/dbhome_1234567/md5
$ echo "${a//dbhome_+([[:digit:]])/dbhome_*}"
/var/log/dbhome_*/md5
$ 

Done!

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104