【问题标题】:Running Unix shell script to split, rename & append record count header to multiple files运行 Unix shell 脚本将记录计数标题拆分、重命名和附加到多个文件
【发布时间】:2016-08-18 14:47:45
【问题描述】:

我有一个大文件需要拆分成 80000 条记录,我可以这样做

split -l 80000 filename.out new_file

这会将所有文件拆分为new_fileaanew_fileabnew_fileac 等...运行后我需要在每个文件中添加一个标题h(recordcount)。所以除了最后一个文件之外,所有文件的标题都是h80000

我想我需要查找文件的最小wc -l 并为该文件创建一个自定义标头。然后所有带有wc -l = 到 80000 的文件我可以将一个通用的h80000 头文件连接到。请协助编写此脚本。

【问题讨论】:

    标签: shell file csv unix


    【解决方案1】:

    你可以这样做:

    #!/bin/sh
    set -e
    count=80000 # How many records per file it is that we want.
    
    split -l "$count" filename.out new_file
    for file in new_file*; do
        mv "$file" temp
        echo "h$count" > "$file"
        cat temp >> "$file"
    done
    rm temp
    # $file is now the filename of the last file.
    last_count="$(expr "$(wc -l "$file" | cut -d' ' -f 1)" - 1)"
    # Replace, e.g., h80000 in the last file with the actual number of records
    # it contains.
    sed -i "s/h$count/h$last_count/" "$file"
    

    【讨论】:

      【解决方案2】:

      这就是我最终的结果:

      split -l 80000 filename.out new_file
      
      
      
      for file in $(ls /path/to/directory/new_file*);
      
      do
              line_count=$(wc -l $file | awk ‘{print $1}’);
              perl -pi -e "print \"h$line_count\n\" if $.==1" $file;
      done
      

      这为所有文件创建了标题,包括不是 80,000 的记录数。感谢您的回复。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-14
        • 1970-01-01
        • 2021-11-30
        • 2013-05-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多