0

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

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

感谢您提前帮助我:)

4

2 回答 2

0
#!/bin/sh

awk '/^SCRIPT_NAME:/ { split( $0, a, ":" ); name=a[2]; next }
    name { print > name ".txt" }' ${1?No input file specified}
于 2012-12-13T21:28:04.197 回答
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
于 2012-12-13T16:32:02.137 回答