【问题标题】:Extracting specific text from a text file in UNIX从 UNIX 中的文本文件中提取特定文本
【发布时间】:2023-03-25 13:44:01
【问题描述】:

我在使用 UNIX shell 脚本时遇到了一些问题,尤其是文件读取。我希望最终产品是脚本将文本文件作为命令行参数,然后提取某些部分以用于各种操作。文本文件如下所示:

ABC12345:John Smith:78
DEF12345:Jane Doe:80
GHI12345:Bob Johnson:91

它会像其他几行一样继续。现在我到目前为止所做的提取最后一个冒号后的数字在这段代码 sn-p 中:

case $1 in

   m)cat $2 | while read -r file; do
   #gets the numbers from 0 to 100
   current=grep [0-100]

case 语句只是因为最终用户将能够以不同的方式运行程序。然而,代码段的主要思想是获取文本文件中行尾的 2 位数字并将其存储在当前变量中。

其余的操作确实围绕这个想法,但是,我不完全确定如何提取中间的名称。

无论如何,任何帮助都会很棒!请记住,我对此很陌生。

【问题讨论】:

标签: shell unix scripting


【解决方案1】:

正如 frankc 所建议的,awk 或 cut 可以很好地工作。你也可以摆弄IFS 和(假设是 Bash)数组:

_old_ifs="$IFS"
IFS=":"
ID_NAME_GRADE=( $LINE )
IFS="$_old_ifs"

echo "Hello ${ID_NAME_GRADE[1]}, your grade is ${ID_NAME_GRADE[2]}"

【讨论】:

    【解决方案2】:

    试试这个:

    $ while IFS=: 读 a b c;回声 $c;完成

    这将回显每行的第三个字段。修改以满足您的需求。

    【讨论】:

      【解决方案3】:

      根据您的情况,有很多方法可以提取姓名和分数。见例子:

      kent$  cat t
      ABC12345:John Smith:78
      DEF12345:Jane Doe:80
      GHI12345:Bob Johnson:91
      
      #using awk 
      kent$  awk -F: '{print "name="$2,", score="$3}' t                                         
      name=John Smith , score=78
      name=Jane Doe , score=80
      name=Bob Johnson , score=91
      
      #using cat
      kent$  sed -r 's/[^:]*?:([^:]*):([0-9]*)$/name=\1, score=\2/g' t
      name=John Smith, score=78
      name=Jane Doe, score=80
      name=Bob Johnson, score=91
      
      #or just catch it directly with grep
      kent$  grep -Po  "(?<=:)[^:]*(?=:)|(?<=:)\d+$" t
      John Smith
      78
      Jane Doe
      80
      Bob Johnson
      91
      

      cut 也可以。

      【讨论】:

        【解决方案4】:

        AWk -F: '{print $NF}' 文件名

        【讨论】:

          猜你喜欢
          • 2012-09-17
          • 2011-06-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-23
          相关资源
          最近更新 更多