Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substitute text with equal length using sed

Is there a way to replace a pattern with equal length of somethings else (e.g. dots, zeros etc.) using sed? Like this:

maci:/ san$ echo "She sells sea shells by the sea shore" | sed 's/\(sh[a-z]*\)/../gI'
.. sells sea .. by the sea ..

("I" requires a newer version of sed to ignore case)
This was easy: the word that starts with "sh" is replaced by double dots (..) but how do I make it something like this: ... sells sea ...... by the sea .....

Any idea? Cheers!

like image 954
MacUsers Avatar asked Apr 14 '13 23:04

MacUsers


2 Answers

My suspicion is that you can't do it in standard sed, but you could do it with Perl or something else with more powerful regex handling.

$ echo "She sells sea shells by the sea shore" |
> perl -pe 's/(sh[a-z]*)/"." x length($1)/gei'
... sells sea ...... by the sea .....
$

The e modifier means that the replacement pattern is executable Perl script; in this case, it repeats the character . as many times as there are characters in the matched pattern. The g modifier repeats across the line; the i modifier is for case-insensitive matching. The -p option to Perl prints each line after the processing in the script specified by the -e option — the substitute command.

like image 143
Jonathan Leffler Avatar answered Oct 01 '22 12:10

Jonathan Leffler


does this awk-oneliner do the job for you?

awk '{for(i=1;i<=NF;i++)if($i~/^[Ss]h/)gsub(/./,".",$i)}1' file

test with your data:

kent$  echo "She sells sea shells by the sea shore"|awk '{for(i=1;i<=NF;i++)if($i~/^[Ss]h/)gsub(/./,".",$i)}1'
... sells sea ...... by the sea .....
like image 21
Kent Avatar answered Oct 01 '22 12:10

Kent