【问题标题】:Remove newline if preceded with specific character on non-consecutive lines如果在非连续行上以特定字符开头,则删除换行符
【发布时间】:2019-10-27 11:15:32
【问题描述】:

我有一个文本文件,每隔一行以 % 字符结尾。我想找到模式“% + 换行”并将其替换为“%”。换句话说,我想删除 % 之后的换行符,而不是其他换行符。

例如,我想更改以下内容:

abcabcabcabc%
123456789123
abcabcabcabc%
123456789123

abcabcabcabc%123456789123
abcabcabcabc%123456789123

我尝试了以下 sed 命令,但无济于事。

sed 's/%\n/%/g' < input.txt > output.txt

【问题讨论】:

  • 试试sed '/%$/{N;s/%\n/%/}' file &gt; output。如果没有以% 结尾的连续行,则应该这样做。

标签: bash unix sed replace


【解决方案1】:

您的数据样本表明没有多个以% 结尾的连续行。

在这种情况下,您可以使用

sed '/%$/{N;s/\n//}' file.txt > output.txt

它的工作原理如下:

  • /%$/ - 查找所有以 % 结尾的行
  • {N;s/\n//} - 一个块:
    • N - 将换行符添加到模式空间,然后将下一行输入附加到模式空间
    • s/\n// - 删除当前模式空间中的换行符。

请参阅online sed demo

【讨论】:

  • 你就不能s/\n//吗?这不像是有多个换行符可供选择。
  • @BenjaminW。是的,没错,这只是在正则表达式方面三重确定一切的习惯。
【解决方案2】:

默认情况下 sed 不能删除换行符,因为它一次读取一个换行符分隔的行。

对于任何数量的以% 结尾的行,在每个 UNIX 机器上的任何 shell 中使用任何 awk,无论是否连续:

$ awk '{printf "%s%s", $0, (/%$/ ? "" : ORS)}' file
abcabcabcabc%123456789123
abcabcabcabc%123456789123

并带有连续的% 行:

$ cat file
now is the%
winter of%
our%
discontent

$ awk '{printf "%s%s", $0, (/%$/ ? "" : ORS)}' file
now is the%winter of%our%discontent

【讨论】:

    【解决方案3】:

    在支持任意数量的连续行的便携式 sed 中:

    parse.sed

    :a                # A goto label named 'a'
    /%$/ {            # When the last line ends in '%'
      N               # Append the next line
      s/\n//          # Remove new-line
      ta              # If new-line was replaced goto label 'a'
    }
    

    像这样运行它:

    sed -f parse.sed infile
    

    infile 包含您的输入和 Ed Morton 回答的输入时的输出:

    abcabcabcabc%123456789123         
    abcabcabcabc%123456789123
    now is the%winter of%our%discontent
    

    【讨论】:

      猜你喜欢
      • 2012-11-15
      • 2022-11-28
      • 2020-11-21
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 2021-12-26
      相关资源
      最近更新 更多