Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 删除支架后的尾部空间_Regex_Bash_Shell_Sed - Fatal编程技术网

Regex 删除支架后的尾部空间

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)追加到模式空间,然后将换行符

我试图使用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
)追加到模式空间,然后将换行符
\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()