运行Unix shell脚本进行拆分,重命名&将记录计数标题附加到多个文件

时间:2016-08-18 14:47:46

标签: shell file csv unix

我有一个大文件,我需要分成80000条记录,我可以通过

完成
split -l 80000 filename.out new_file

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

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

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分:0)

这就是我最终的结果:

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的记录计数。感谢您的回复。