如何使用 Linux/Unix 将文本文件中以某个字符开头的行替换为空行?

发布于 2025-01-13 13:23:43 字数 300 浏览 0 评论 0原文

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

eeeeee
<
<
aaaa
bbbb
cccc
<
dddddd
<
ff

我想要这样:(

eeee

aaaa
bbbb
cccc

dddddd

ff

如果有多个连续 < 行,理想情况下只需要一个空行)

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

I'm using Ubuntu and have a large text file where certain rows start with < character what I'd like to replace each of these to an empty row. So from this:

eeeeee
<
<
aaaa
bbbb
cccc
<
dddddd
<
ff

I want this:

eeee

aaaa
bbbb
cccc

dddddd

ff

(In case of multiple consecutive < rows only one empty rows is needed ideally)

How to perform this in command line?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天冷不及心凉 2025-01-20 13:23:43

这个 Perl 一行代码应该可以满足您的要求:

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;
}

This Perl one-liner should do what you're asking for:

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

Here it is in action:

# 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

Commented code:

# 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;
}
尬尬 2025-01-20 13:23:43

你可以使用 sed。在这种情况下,命令将类似于:
sed '/
这将找到带有“<”的行字符开头,并将该行替换为空。但是,它不会用单行替换多个空行。

You could use sed. In this case the command would look something like:
sed '/</c\\' file.txt
This would find a line with a '<' character at the beginning, and replace the line with nothing. It would not however replace multiple empty rows with a single row.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文