使用bash逐行读取文件,提取一些数据。怎么样?

时间:2012-12-13 16:24:06

标签: parsing shell text-extraction

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

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个描述文件。

感谢您提前帮助我:)

2 个答案:

答案 0 :(得分:0)

使用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

答案 1 :(得分:0)

#!/bin/sh

awk '/^SCRIPT_NAME:/ { split( $0, a, ":" ); name=a[2]; next }
    name { print > name ".txt" }' ${1?No input file specified}