【问题标题】:Reading a file line by line using bash, extracting some data. How?使用 bash 逐行读取文件,提取一些数据。如何?
【发布时间】:2012-12-13 16:24:05
【问题描述】:

我想根据某个标签读取文件并从中提取信息。例如:

SCRIPT_NAME:mySimpleShell.sh

This is a simple shell. I would like to have this as
Description. I also want to create a txt file our of this.

SCRIPT_NAME:myComplexShell.sh

This is a complex shell. I would like to have this as
Description. I also want to create a txt file our of this.

所以当我将此文件传递给我的 shell 脚本时,我的 shell 将逐行读取它并 当它到达 SCRIPT_NAME 时,将其提取并保存在 $FILE_NAME 中,然后开始写入 磁盘上具有 $FILE_NAME.txt 名称的文件的描述。它会一直这样做,直到它到达文件的末尾。如果有 3 个 SCRIPT_NAME 标签,则创建 3 个描述文件。

感谢您提前帮助我:)

【问题讨论】:

    标签: parsing shell text-extraction


    【解决方案1】:

    使用while 循环读取行。使用正则表达式检查一行是否有SCRIPT_NAME,如果有,提取文件名。如下所示:

    #! /bin/bash
    while IFS= read -r line
    do
        if [[ $line =~ SCRIPT_NAME:(.*$) ]]
        then
            FILENAME="${BASH_REMATCH[1]}"
            echo "Writing to $FILENAME.txt"
        else
            echo "$line" >> "$FILENAME.txt"
        fi
    done < inputFile
    

    【讨论】:

      【解决方案2】:
      #!/bin/sh
      
      awk '/^SCRIPT_NAME:/ { split( $0, a, ":" ); name=a[2]; next }
          name { print > name ".txt" }' ${1?No input file specified}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-20
        • 2012-01-24
        • 1970-01-01
        相关资源
        最近更新 更多