2017-10-12 66 views
1
$ cat testfile 
first line mark apple 
second line not banana 
third line mark pear 

我想循环每一行文件。如果它包含mark则显示整行而不会占用空间。如何在不丢失for循环中的空间的情况下回显变量?

,但如果我的代码如下,它把空间分成回报:

for i in `cat testfile | grep mark`; do 
    echo $i 
done 

输出

first 
line 
mark 
apple 
third 
line 
mark 
pear 

如果用printf

for i in `cat testfile | grep mark`; do 
    printf $i 
done 

输出

firstlinemarkapplethirdlinemarkpear 

我怎么能得到的输出如下:

first line mark apple 
third line mark pear 
+0

grep的标志testfile的 – xxfelixxx

+0

我正要建议'因为我在 “$(grep的标志testfile的)”;做回声“$我”; done',但它将'$ i'设置为'grep'命令的整个多行输出,而不是按行迭代。 –

回答

2

这应该是OK:

grep mark testfile 
2

最简单的方法是:

grep mark testfile 

没有循环需要。并且没有useless use of cat


但是,如果你想知道为什么你的循环是不行的,那是因为你在grep的输出循环每。遍历每个线你需要使用read

cat testfile | grep mark | while read line; do 
    echo "$line" 
done 

while read line; do 
    echo "$line" 
done <(cat testfile | grep mark) 

其实是完全安全的,我们应该加上IFS=read -r妥善保存所有的空格和反斜杠。

cat testfile | grep mark | while IFS= read -r line; do 
    echo "$line" 
done 

虽然这是很多不必要的代码。读每一行只是为了吐出来?最好只是省略整个循环。

+0

这很完美。但是另外,在grep之后,我的脚本需要循环结果,并将最后一个单词放入函数中以测试它的模式,如果匹配,则打印整行。如果是这种情况,我应该在'grep mark testfile'中使用我;做?我害怕这样,它又分裂了? –

1

谢谢大家的回复,之后转换成grep的模式文件,该脚本如下,让我知道这是否是一个合适的:

grep pattern file | while read line; do 
    ip=`echo $line | cut -d ' ' -f 8` 
    fqdn=`echo $line | cut -d ' ' -f 6` 
    grepcidr -v -f /root/collect/china_routes.txt <(echo $ip) >/dev/null 
    if [ $? == 0 ]; then 
     grep $fqdn fqdnfile || echo $fqdn >> /root/collect/fqdn 
    fi 
done 

以上正试图看看“模式”现身在任何文件行中,然后它将第八个字段作为ip,第六个字段作为fqdn(因为该行由空格分隔);那么它将通过grepcidr检查$ ip是否在cidr范围内,如果它不在范围内(-v),那么检查$ fqdn是否已存在于fqdnfile文件中,如果它不在文件中,则echo $ FQDN到该文件

文件本身看起来像如下:

Oct 11 20:19:05 dnsmasq[30593]: reply api.weibo.com is 180.149.135.176 
Oct 11 20:19:05 dnsmasq[30593]: reply api.weibo.com is 180.149.135.230 
Oct 11 20:19:06 dnsmasq[30593]: query[A] sina.com from 180.169.158.178 
Oct 11 20:19:06 dnsmasq[30593]: forwarded sina.com to 114.114.114.114 
Oct 11 20:19:06 dnsmasq[30593]: reply sina.com is 66.102.251.33 
Oct 11 20:19:06 dnsmasq[30593]: query[PTR] 74.103.225.116.in-addr.arpa from 127.0.0.1 
Oct 11 20:19:06 dnsmasq[30593]: cached 116.225.103.74 is NXDOMAIN-IPv4 
相关问题