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

Time:04-07

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?

CodePudding user response:

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

CodePudding user response:

I think

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

should do it.

CodePudding user response:

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.)

  • Related