2016-06-09 56 views
2

这是一种新的linux学习者,需要您的帮助。 此代码如何从文件中读取每一条匹配的文件分割线

sed 's/regexp/&\n/g' file.txt 

只在第一场比赛的作品给人的第一场比赛中只输出,然后停止读取行的其余部分。

如果我想继续阅读直到结束并在每场比赛中将线移动到新线,该怎么办?

比如我有一个像下面

some text here Critical and some text here Critical and again some text here Critical. 

一个日志文件,我想打破它像下面

some text here 
Critical and some text here 
Critical and again some text here 
+2

只要用'&n换掉'&'并说'sed's/Critical/\ n&/ g'file'。 – fedorqui

+0

使用我给出的第二种方法,它更便于携带。 – khrm

+0

谢谢,只是添加“&”工作。 – Hamad

回答

1

你必须使用g下全球变化。

echo "some text here Critical and some text here Critical and again some text here Critical." | sed -e 's:Critical:\nCritical:g' 

Eventhough这会工作,我会建议你使用这样的:

echo "some text here Critical and some text here Critical and again some text here Critical." | sed -e 's:Critical:\ 
> Critical:g' 

在哪里>是提示字符。你不必使用它。你会得到的。这是使用sed更换新行的便携方式。所有其他方式都不便携。

从文件中读取:

sed -e 's:Critical:\ 
Critical:g' file 
+0

但我需要从文件中读取文本。 sed's/Critical/\ n&/ g'文件 上面的逗号工作了 – Hamad

+0

您也可以使用第二个文件从文件中读取文本。如果它工作,然后upvote和accpet。我改变了sed。两者在linux中都是一样的。 – khrm

+0

@Hamad我也添加了文件。 – khrm

1

你可以试试这个Perl的一行代码:

cat file.txt | perl -ne 'chomp; @y = split(/Critical/, $_); print join("\nCritical", @y) . "\n"' 

这是假设file.txt的内容仅仅是一个长线这样你表示:

some text here Critical and some text here Critical and again some text here

输出:

some text here 
Critical and some text here 
Critical and again some text here 
相关问题