I have many files with lines like:
[random strings] /a/given/path [random strings]
I would like to replace the /a/given/path
by a pattern like XXXXXXXXXXXXX
, the number of X
being the size of the /a/given/path
.
Say [random strings] does not contain the text to be matched (there is only a single occurrence of the searched string in the file)
I know how to replace it by a single X
using sed 's|/a/given/path|X|g'
but I don't get how to get the correct number of X depending on the input path length.
Ideally, I would rely on a single sed command, no scripting around, (but may be a acceptable fall back if not feasible with a single sed)
This might work for you (GNU sed):
sed -E ':a;\#/a/given/path#{s//\n&\n/;:b;s/^([^\n]*)\n[^\n]/\1X\n/;tb;s/\n//g;ba}' file
Erect some scaffolding around the /a/given/path
, in this case newlines.
Replace every character between the scaffolding with X
's.
Remove the scaffolding i.e. the newlines.
In more depth:
Find /a/given/path
and surround that string with newlines (newlines are used since they cannot appear naturally as sed is line based).
Using iteration and substitution replace each character between the newlines with X
.
Remove the newlines and go again.
N.B. The usual search regexp uses the /
delimiter but in this case because we know the target includes this character an alternative is used instead \#...#
i.e. the hash character.