如何用 Linux/Unix 替换文本文件中以空行开头的特定字符的行?

How to replace rows starting with a certain character with emptly lines in text file with Linux/Unix?

我正在使用 Ubuntu 并且有一个大文本文件,其中某些行以 < 字符开头,我想将其中的每一行替换为一个空行。所以从这个:

eeeeee
<
<
aaaa
bbbb
cccc
<
dddddd
<
ff

我想要这个:

eeee

aaaa
bbbb
cccc

dddddd

ff

(在多个连续 < 行的情况下,理想情况下只需要一个空行)

如何在命令行中执行此操作?

你可以使用 sed。在这种情况下,命令看起来像: sed '/</c\' file.txt 这将找到开头带有“<”字符的行,并将该行替换为空行。但是,它不会用一行替换多个空行。

这个 Perl one-liner 应该可以满足您的要求:

perl -ne 'if (/^</) {print "\n" if !$f; $f=1} else {$f=0; print}' tmp.txt

这是实际操作:

# cat tmp.txt
eeeeee
<
<
aaaa
bbbb
cccc
<
dddddd
<
ff
# perl -ne 'if (/^</) {print "\n" if !$f; $f=1} else {$f=0; print}' tmp.txt
eeeeee

aaaa
bbbb
cccc

dddddd

ff

注释代码:

# Found a line starting with '<'
if (/^</) {
    # Print a blank line if $f is false
    print "\n" if !$f;
    # Set $f to true so subsequent lines starting with '<' are ignored
    $f=1;
} else {
    # Not a line starting with '<'; reset $f to false
    $f=0;
    # Print the current line
    print;
}