如何使用sed或grep从文件中提取文本?

时间:2015-11-21 09:29:03

标签: sed grep extract

我的示例字符串位于txt文件/www/meteo/last.txt:

<nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button class="navbar-toggle collapsed" aria-expanded="false" aria-controls="navbar" type="button" data-toggle="collapse" data-target="#navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Project name</a> </div> <div class="navbar-collapse collapse" id="navbar"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> <li class="dropdown"> <a class="dropdown-toggle" role="button" aria-expanded="false" aria-haspopup="true" href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider" role="separator"></li> <li class="dropdown-header">Nav header</li> <li><a href="#">Separated link</a></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="../navbar/">Default</a></li> <li><a href="../navbar-static-top/">Static top</a></li> <li class="active"><a href="./">Fixed top <span class="sr-only">(current)</span></a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> <!--This should not cover up the navbar--> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button class="navbar-toggle collapsed" aria-expanded="false" aria-controls="navbar" type="button" data-toggle="collapse" data-target="#navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Toolbar</a> </div> <div class="navbar-collapse collapse" id="navbar"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Item 1</a></li> <li><a href="#about">Item 2</a></li> <li><a href="#contact">Item 3</a></li> </ul> </div><!--/.nav-collapse --> </div> </nav>

我想从该文件中逐行获取3个数字到新文件。 (这些值是温度所以它们随时间变化 - 每10分钟一次)

新文件/www/meteo/new.txt :(逐行)

a:3:{i:0;s:4:"6.13";i:1;s:5:"19.94";i:2;s:5:"22.13";}

2 个答案:

答案 0 :(得分:0)

试试这个awk方法

awk -F'"' 'BEGIN{OFS="\n"} {print $2,$4,$6}' last.txt  > new.txt

<强>输出:

cat new.txt
6.13
19.94
22.13

答案 1 :(得分:0)

或者,如果您想使用sedgrep

sed -r 's/([^"]*)("[^"]*")([^"]*)/\2\n/g;s/"//g' /www/meteo/last.txt

grep -Eo '"[^"]*"' /www/meteo/last.txt | sed 's/"//g'

如果您想要一个特定值,请说出引号中的第二个温度,您可以使用sed

grep -Eo '"[^"]*"' /www/meteo/last.txt | sed -n '2p'