LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1481|回复: 7

如何批量提取文本文件中固定行的数字

[复制链接]
发表于 2004-11-14 22:26:52 | 显示全部楼层 |阅读模式
有一堆文本文件,想把其中固定行固定位置的数据提取出来,该怎么办呢?
发表于 2004-11-15 19:11:39 | 显示全部楼层
建议用C编写一个小程序line,读出某个行,然后用cut命令取出指定的字段,如果文件多就用for循环。
发表于 2004-11-15 20:04:51 | 显示全部楼层
编写C文件: getline.c
/*
*  this is a file that can read a line from a file
*/

#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

#define MAX_CHARS       1024

char    usage[]="Usage: line [-n <Line number>] <filename>\n       -h: help\n";

static int isnumber(const char*);

int main(int argc, char* argv[])
{
        int line = 1;
        char filename[MAX_CHARS] = {0};
        char buffer[MAX_CHARS];
        int fd;
        int i;
        int status;
        struct stat st;

        if ( argc < 2 ) {
                printf(usage);
                return 1;
        }

        if (strcmp(argv[1], "-n") == 0) {
                if (isnumber(argv[2]))
                        line = atoi(argv[2]);
                else {
                        printf(usage);
                        return 1;
                }
                strcpy(filename, argv[3]);
        }
        else
                strcpy(filename, argv[1]);
        if (stat(filename, &st)) {
                perror("Error: ");
                return 1;
        }
        if (!S_ISREG(st.st_mode)) {
                printf("Error: must need regular file\n");
                return 1;
        }

        fd = fopen(filename, "r");

        for (i = 0; i < line; ++i) {
                if (!fgets(buffer, MAX_CHARS, fd)) {
                        printf("Error: out of line ranger");
                        return 1;
                }
        }

        printf(buffer);

        return 0;
}

int isnumber(const char* s)
{
        int i;
        for (i = 0; i < strlen(s); ++i)
                if (!isdigit(s))
                        break;
        if (i == strlen(s))
                return 1;
        else
                return 0;
}

编译:
gcc -o getline getline.c

cp getline /usr/bin/

写提取字段的脚本:
echo "$(getline -n 行号 文件名 | cut -c起始列号-截止列号)"

代码写的不是很好,应该用getopt来提取命令行选项。
发表于 2004-11-16 08:16:37 | 显示全部楼层
其中固定行固定位置的数据,,能例子说说?。。
 楼主| 发表于 2004-11-16 09:55:43 | 显示全部楼层

谢谢,我看看

第一行 21 32 43 59 01
第二行 53 40 32 01 49
第三行 04 21 12 30 09
等等
现在要提取第3行,第2列的数据
就是这样
 楼主| 发表于 2004-11-16 10:02:21 | 显示全部楼层
不过前几天自己想出来了个笨办法,给大家说说吧
先用sed -n '/第三行/p' filename 提取出第三行
然后用cut -c起始列号-截止列号 提取想要得元素
不过就是一个个的提取太累了,那位能想个高明点的方法?
让他从100个文件中自动提取
发表于 2004-11-16 13:50:16 | 显示全部楼层
假设 t1 是其中的一个文件
$ sed -n '3p' t1 | cut -d ' ' -f2
得到 要的值 (第三行,第二列 如果用tab 分列,可以不用 -d)

如果有多个文件可以用一个 for
$for f in t*; do sed -n '3p' "$f" | cut -d ' ' -f2 >> res; done

t* 为你的数据文件s, res 为得到结果
 楼主| 发表于 2004-11-16 14:40:28 | 显示全部楼层
谢谢,搞定了
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表