Kay
Kay

Reputation: 2077

How to replace * in sed

I would like to replace * with a number.

ifile.txt
2 3 4 *****
3 3 4 *****
1 2 1 *****

desire output

ofile.txt
2 3 4 999
3 3 4 999
1 2 1 999

I was trying with

sed -i 's/*****/999/g' ifile.txt

But not working.

Upvotes: 1

Views: 269

Answers (5)

Claes Wikner
Claes Wikner

Reputation: 1517

You can do this with gawk. The following code replaces the asterisks in fourth column with three nines.

gawk '{gsub(/*****/,"999",$4)}1' file 
        2 3 4 999
        3 3 4 999
        1 2 1 999

Upvotes: 1

slitvinov
slitvinov

Reputation: 5768

$ cat t.awk 
function sgsub(r, t, s,    m, i, prefix, ans) { # substitutes `t' for
                                                # all occurence of the
                                                # string `r' in the
                                                # string `s'
    m = length(t)
    while (i = index(s, r)) {
       prefix  = substr(s, 1    , i-1)
       s       = substr(s, i + m     )
       ans     = ans prefix t
    }
    ans = ans s
    return ans
}

BEGIN {
    old = "*****"
    new = "99999"
}

{
    print sgsub(old, new, $0)
}

Usage:

echo '2 3 4 *****' | awk -f t.awk
awk -f t.awk infile.txt

Upvotes: 1

lamp76
lamp76

Reputation: 333

Without -r could not work

If you need to replace exactly 5 * with 999.You can also use this:

sed -r 's/\*+/999/g' ifile.txt

In regular expressions + is used to match one or more consecutive repetition of

sed -r 's/\*{5}/999/g' ifile.txt

In regular expressions {n} is used to match exactly n consecutive repetition of

sed -r 's/\*{2,5}/999/g' ifile.txt

In regular expressions {n,m} is used to match minimum n and maximum m consecutive repetition of

To be sure that your expression work as your expectation use -r, because sed standard expression (a reduced rule set) vary from unix/linux distribution, so use -r to be sure that all the regular expression rules will be applied (without the need of escaping +,{,},(,) special chars).

Upvotes: 1

Pedro Lobito
Pedro Lobito

Reputation: 99071

You need to escape the special character * using \, i.e.:

 sed -i 's/\*+/999/g' ifile.txt

Will match 1 or more * (\*+) and replace it with 999

Upvotes: 4

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26141

Try

sed -i 's/\*\*\*\*\*/999/g' ifile.txt

Because * is one of the most basic special characters in RE. See POSIX BRE and directly from specification see QUOTED_CHAR.

Upvotes: 1

Related Questions