Regex 删除支架后的尾部空间
我试图使用sed(CentOS上shell脚本的一部分)删除HTML文件中括号后的尾随空格: 由此:Regex 删除支架后的尾部空间,regex,bash,shell,sed,Regex,Bash,Shell,Sed,我试图使用sed(CentOS上shell脚本的一部分)删除HTML文件中括号后的尾随空格: 由此: <p>Some text ( <em>Text which should not break to a new line</em>). More text.</p> 还有很多其他的东西,但都不管用 有什么想法吗?试试: sed ':a;/($/{N;s/\n//;ba}' file 如果行以()结尾,则将下一行(N)追加到模式空间,然后将换行符
<p>Some text (
<em>Text which should not break to a new line</em>). More text.</p>
还有很多其他的东西,但都不管用
有什么想法吗?试试:
sed ':a;/($/{N;s/\n//;ba}' file
如果行以(
)结尾,则将下一行(N
)追加到模式空间,然后将换行符\N
替换为零,从而连接行。这是在循环中完成的(ba
跳回标签a
)。
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()
曾经有过同样的问题。
tr
是代替sed的方法:
cat textfile.ext | tr-d'\n'
这将删除文件中的所有换行符(-d
),或者您甚至可以先使用grep
过滤掉相关行
cat textfile.ext | grep-A1'^Some text'| tr-d'\n'
选项-A1
表示使用regexp缓存的行之后的n
行^..
。有关更详细的说明,请参阅man grep
编辑:在您的特殊情况下,grep
命令应该更像这样:grep-A1'($”
,它使用以下行过滤行末尾的所有打开的父项(见上文).你的意思是删除换行符吗?结尾处的7
是什么?只是打印的一种替代方法。@Babyy在awk中,非零数字将被视为布尔true
,并触发默认操作,即打印。我觉得按7
,您可以给出1
,8
,或134123142
为什么要跳回标签?以及ba
中的b
是什么?检查sed
手册。a
是标签,b标签
表示“分支到标签”。这将创建一个循环。谢谢,我从您的代码中删除了:a
和ba
,结果是相同的;为什么要使用标签?请尝试使用一个文件测试它,该文件有三个连续的行,以结尾(
。如果不使用循环,它们将不会加入一行。请使用-i
选项更新文件,即sed-i转换文件
kent$ sed 's/$/|/' f
foo [with trailing spaces]( |
)foo end|
bar [with trailing spaces & tab]( |
)bar end|
blah no trailing spaces(|
)|
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()