>Newbie question here. I was trying to replace some text of the file
>with equal amount of blank spaces via sed. I have been looking to all
>the groups but I have not seen this one done.
>I was able to do it but I did a dumb substitution with 55 actual
>spaces. Is there an actual command that would insert 55 spaces (or
>whatever other number)?
>Here is what I used:
> /' file_name.txt >> file_name_new.txt
Probably the neatest way to do something like this is
to use perl;
perl -pe 's/(customerName.*\*Length:136)/" " x length($1)/e'
Using 'perl' also gives you the option to make the '.*'
non-greedy -Usually * eats up as many characters as it
can and then the matching will work backwards so in this
case if there were 2 "*Length:136" strings on the line
the expression would macth the last one. You can make it
match the last by using the non-greedy '?' modifier;
perl -pe 's/(customerName.*?\*Length:136)/" " x length($1)/e'
To do it with 'sed' the only way I can see at the moment
is somewhat complicated and would involve isolating the
regular expression match, seperating it from the entire
string itself and using an s/./ /g to translate every
character to a SPACE, then inserting it back into the string.
This is an example way you could do that although it's
not exactly functionally equivalent to the code you
posted (because the initial .* means the pattern will
match the last customerName on the line if there are
more than one) ;
# hold space = original string
# if there is no match exit so the line gets printed as normal
# pattern space = matched text only
# translate text into SPACEs
# hold space = SPACEs, pattern space = original string
# delete text from string leaving a NEWLINE to mark its position
# append the SPACEs to insert to the end of the main string,
# so now the pattern space is: LEFT SIDE TEXT \n RIGHT SIDE TEXT \n SPACEs
# move the SPACEs into the marker position
Well, that's probably a bit horrific looking if you're a newbie
in fact it's horrific looking anyway!! - so it's best to use 'perl'
who loves these sorts of problems, or even 'awk' is better.
Here's a way to do it in 'awk';