Federcio2
Federcio2

Reputation: 89

Replace first four characters of a string

I would need to mask, with Regular Expression in Sed Editor, a string after 4 characters.

Example: 1234567890
Result: 1234XXXXXX

Can you help me?

Upvotes: 1

Views: 273

Answers (5)

ctac_
ctac_

Reputation: 2491

With sed

count=4
echo "1234567890" | \
sed ':A;s/\(\(.\)\{'"$count"'\}\)\(X*\)[^X]/\1\3X/;tA'

or

sed -E ':A;s/((.){'"$count"'})(X*)[^X]/\1\3X/;tA'

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247012

With perl, you can put arbitrary perl code in the replacement text:

perl -pe 's/^(....)(.*)/$1 . "X" x length($2)/e' <<END
1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
END
1
12
123
1234
1234X
1234XX
1234XXX
1234XXXX
1234XXXXX
1234XXXXXX

Upvotes: 0

Hazzard17
Hazzard17

Reputation: 723

In GNU sed:

echo "1234567890" | sed "s/./X/5g"

Upvotes: 2

Kent
Kent

Reputation: 195199

$echo "1234567890"|awk '{for(i=5;i<=NF;i++)$i="X"}7' FS="" OFS=""
1234XXXXXX 

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133640

Following awk may help you here.

echo "1234567890" | awk '{for(i=5;i<=length($0);i++){val=val?val "X":"X"};print substr($0,1,4) val;val=""}'

Output will be as follows.

1234XXXXXX

Upvotes: 0

Related Questions