'Replace a line starting with '-' hyphen with a character repeated n times

I have a text file that has some lines like this (hyphen repeated)

-------------------------------------------------------

I need to replace these lines with character 'B' repeated 1500 times. For example, like

BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB

Any suggestions using 'sed' or 'awk' command?



Solution 1:[1]

With awk:

$ awk '/^-+$/ {s = sprintf("% 1500s", ""); gsub(/ /,"B",s); print s; next} 1' file

Or, maybe a bit more efficient if you have many such lines:

$ awk 'BEGIN {s = sprintf("% 1500s", ""); gsub(/ /,"B",s)} \
       /^-+$/ {print s; next} 1' file

Solution 2:[2]

I think

perl -pe 'my $bb = "B"x1500; s/^-+$/$bb/g'

should do it.

Solution 3:[3]

printf+sed variant:

$ cat file
1111
----
2222

$ sed -r 's/^-+$/'"$(printf --  "%.1s" B{1..150})/" file
1111
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
2222

Here sed is used only for replacement.
printf is used for generating 1500 times B. (The above scriptlet has 150 instead of 1500, because it required too much scrolling.)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Hellmar Becker
Solution 3 anishsane