将以“-”连字符开头的行替换为重复 n 次的字符

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

我有一个文本文件,其中有一些像这样的行(连字符重复)

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

我需要将这些行替换为重复 1500 次的字符 'B'。比如喜欢

BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB

有使用 'sed' 或 'awk' 命令的建议吗?

我觉得

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

应该做。

awk:

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

或者,如果你有很多这样的行,可能会更有效率:

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

printf+sed 变体:

$ cat file
1111
----
2222

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

这里sed只是用来替换的
printf 用于生成 1500 倍 B。(上面的 scriptlet 有 150 而不是 1500,因为它需要太多滚动。)