【问题标题】:sed remove trailing space after bracketsed 删除括号后的尾随空格
【发布时间】:2014-06-27 09:40:36
【问题描述】:

我正在尝试使用 sed(CentOS 上的 shell 脚本的一部分)删除 HTML 文件中括号后的尾随空格:

从此:

<p>Some text (
<em>Text which should not break to a new line</em>). More text.</p>

到这里:

<p>Some text (<em>Text which should not break to a new line</em>). More text.</p>

我可以在 Sublime Text 中使用 \(\s REGEX 轻松完成,并用括号替换它,但这在 sed 中不起作用。

我试过了:

sed 's/[(]\s*$/(/'
sed 's/[(]\s*$\n/(/'

还有很多其他的东西,但它们都不起作用。

有什么想法吗?

【问题讨论】:

  • 你的意思是删除换行符吗?

标签: regex bash shell sed


【解决方案1】:

试试:

sed ':a;/($/{N;s/\n//;ba}' file

如果行以( 结尾,则将下一行(N)附加到模式空间,然后将换行符\n 替换为空,从而加入行。这是在循环中完成的(ba 跳回标签a)。

【讨论】:

  • 为什么要跳回标签? ba 中的 b 是什么?
  • 查看sed 手册。 a 是一个标签,b label 表示“分支到标签”。这会创建一个循环。
  • 谢谢您,我从您的代码中删除了:aba,结果是一样的;为什么要使用标签?
  • 尝试使用包含三个连续行以( 结尾的文件对其进行测试。如果您不使用循环,它们将不会合并成一行。
  • 使用-i 选项更新文件,即sed -i transformation file
【解决方案2】:

我愿意:

awk 'sub(/\(\s*$/,"("){printf "%s",$0;next}7' file

带/不带尾随空格/制表符的示例:

kent$  cat f
foo [with trailing spaces](     
)foo end
bar [with trailing spaces & tab](               
)bar end
blah no trailing spaces(
)

只是为了显示尾随空格:

kent$  sed 's/$/|/' f
foo [with trailing spaces](     |
)foo end|
bar [with trailing spaces & tab](               |
)bar end|
blah no trailing spaces(|
)|

用我的 awk oneliner 测试:

kent$  awk 'sub(/\(\s*$/,"("){printf "%s",$0;next}7' f
foo [with trailing spaces]()foo end
bar [with trailing spaces & tab]()bar end
blah no trailing spaces()

【讨论】:

  • 最后的7是什么?
  • 只是打印的替代品。
  • @Babyy 在 awk 中,非零数字将被视为布尔值 true。并触发默认操作,即打印。我觉得按7比较方便,可以给18,或者134123142
【解决方案3】:

曾经遇到过同样的问题。 tr 是去这里的方式,而不是 sed

cat textfile.ext | tr -d '\n'

这将删除文件的所有换行符 (-d)。或者您甚至可以先使用grep 过滤掉相关行,例如。

cat textfile.ext | grep -A1 '^&lt;p&gt;Some text' | tr -d '\n'

选项 -A1 代表 n 行在您使用正则表达式 '^&lt;p&gt;... 缓存的行之后。更详细的解释见man grep

编辑:在您的特殊情况下,grep 命令更可能看起来像这样:grep -A1 '($',它使用以下行过滤所有打开的父级(见上文)。

【讨论】:

    猜你喜欢
    • 2017-05-31
    • 2011-05-25
    • 1970-01-01
    • 2013-09-23
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    相关资源
    最近更新 更多