【问题标题】:Bash - get content of fileBash - 获取文件的内容
【发布时间】:2021-04-01 10:24:16
【问题描述】:

我需要在 bash 中获取文件的内容,但我只需要在关键字之前的特定单词。

文件如下所示:

conn NameOfConnection1
    some settings

conn NameOfConnection2
    some settings

conn NameOfConnection3
    some settings

我需要一个 bash 脚本,每行只输出 NameOfConnection1,2,3。

//编辑:

小问题。该文件有这个:

    # It is best to add your IPsec connections as separate files in /etc/ipsec.d/
include /etc/ipsec.d/*.conf

并且一些 conns 在单独的文件夹中。

【问题讨论】:

  • grep 好像是工具,你试过了吗?

标签: linux bash file centos


【解决方案1】:

这里有一个解决方案:

grep '^conn' file.txt | cut -d ' ' -f 2

【讨论】:

  • 那行得通,谢谢,但我忘了小问题,我编辑了这个问题。猜猜可能会为该文件夹中的 .conf 扩展文件循环?
  • grep 可以处理多个文件,无需循环。
【解决方案2】:

使用awk 可以打印/提取所需的输出。

awk '$1 == "conn" {print $2}' file.txt

上面的代码基本上意味着,如果字段/列$1是conn,则打印第二个$2字段/列。

【讨论】:

    猜你喜欢
    • 2015-01-07
    • 2017-08-27
    • 2013-01-16
    • 1970-01-01
    • 2010-11-25
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多