【问题标题】:How to echo variable without losing space in a for loop?如何在 for 循环中回显变量而不丢失空间?
【发布时间】:2018-03-23 18:56:24
【问题描述】:
$ cat testfile
first line mark apple
second line not banana
third line mark pear

我想循环文件的每一行。如果它包含mark,则显示整行而不丢失空间。

但是如果我的代码如下,它会将空格变成返回:

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

【问题讨论】:

  • grep 标记测试文件
  • 我正要建议for i in "$(grep mark testfile)" ; do echo "$i" ; done,但它会将$i 设置为grep 命令的整个多行输出,而不是逐行迭代。

标签: bash shell for-loop echo


【解决方案1】:

这应该没问题:

grep mark testfile

【讨论】:

    【解决方案2】:

    最简单的方法是:

    grep mark testfile
    

    不需要循环。没有useless use of cat


    但是,如果您想了解为什么您的循环不起作用,那是因为您正在遍历 grep 输出中的每个 word。要遍历每一行,您需要使用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
    

    不过,这是很多不必要的代码。阅读每一行只是为了把它们吐出来?最好省略整个循环。

    【讨论】:

    • 太完美了。但另外,在 grep 之后,我的脚本需要循环结果,并将最后一个单词提取到一个函数中以测试它的模式,如果匹配,则打印整行。如果是这种情况,我应该在grep mark testfile 中使用 for i ;做?就怕这样,又分手了?
    【解决方案3】:

    谢谢大家的回复,转换成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
    

    上面是尝试查看'pattern'是否出现在文件的任何一行中,然后它选择第八个字段作为ip,第六个字段作为fqdn(因为该行是用空格分隔的);然后它将通过grepcidr检查$ip是否在cidr范围内,如果不在范围内(-v),则检查$fqdn是否已经存在于fqdnfile文件中,如果不在文件中,则回显$ 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      相关资源
      最近更新 更多