Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace all middle characters with '*'?

Tags:

grep

sed

awk

I would like to replace middle of word with ****.

For example :

ifbewofiwfib
wofhwifwbif
iwjfhwi
owfhewifewifewiwei
fejnwfu
fehiw
wfebnueiwbfiefi

Should become :

if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi

So far I managed to replace all but the first 2 chars with:

sed -e 's/./*/g3' 

Or do it the long way:

grep -o '^..' file > start
cat file | sed 's:^..\(.*\)..$:\1:' | awk -F. '{for (i=1;i<=length($1);i++) a=a"*";$1=a;a=""}1' > stars
grep -o '..$' file > end
paste -d "" start stars > temp
paste -d "" temp end > final
like image 776
MataKiera Avatar asked Dec 18 '22 00:12

MataKiera


1 Answers

I would use Awk for this, if you have a GNU Awk to set the field separator to an empty string (How to set the field separator to an empty string?).

This way, you can loop through the chars and replace the desired ones with "*". In this case, replace from the 3rd to the 3rd last:

$ awk 'BEGIN{FS=OFS=""}{for (i=3; i<=NF-2; i++) $i="*"} 1' file
if********ib
wo*******if
iw***wi
ow**************ei
fe***fu
fe*iw
wf***********fi
like image 120
fedorqui 'SO stop harming' Avatar answered Dec 22 '22 00:12

fedorqui 'SO stop harming'