replace number with star specific pattern for whole file

2

1

In my file I want to replace number to *

Example:

data[0] ---> data[*]

I have data[0] to data[127] and also want to do for the whole file. So how can I do only for number?

I tried with command

sed 's/[[0-9][0-9]]/[*]/g'

but it does not work properly.

So please guide me.

Vishal Patel

Posted 2018-10-09T08:00:45.267

Reputation: 21

why shouldn't it be as simple as sed 's/[0-9]/*/g ? – datdinhquoc – 2018-10-09T08:37:18.293

1It will also affect other number also. Suppose set_load -pin_load 0.5 [get_ports {data[25]}] then it will also change 0.5 to *. – Vishal Patel – 2018-10-09T08:46:23.173

The issue in what you tried is not escaping square brackets when you don't want them to have a special meaning. – simlev – 2018-10-10T12:54:43.850

Answers

0

This will replace all digits inside square brackets to asterisks:

sed 's/\[[0-9]*\]/\[*\]/g'

datdinhquoc

Posted 2018-10-09T08:00:45.267

Reputation: 201

1I believe there's no need to escape the square brackets in the replacement section, as they have no special meaning there. – simlev – 2018-10-10T12:55:16.080

0

Answer: Here's how you could amend your tentative SED expression (sed 's/[[0-9][0-9]]/[*]/g'):

sed -E 's/\[[0-9]{1,3}]/[*]/g'

Explanation:

  • escape the initial square bracket [ with a backslash \ because you want the expression to match a literal [ as opposed to any of the characters you write between square brackets. Subsequent square brackets do not need escaping.

  • specify how many digits you want to match: {1,3} means any natural number starting with 1 and up to 3. For this to work, you need to enable extended regular expressions with the -E switch (without it you could be content with sed 's/\[[0-9]*]/[*]/g'). It should be available in your sed since, according to man sed:

    the -E option has been supported for years by GNU sed, and is now included in POSIX.


Perl alternative here:

perl -pe 's/data\[\K\d+(?=])/*/g'

simlev

Posted 2018-10-09T08:00:45.267

Reputation: 3 184