我需要将一个大的已排序文件拆分为较小的块,每个文件包含一个已排序的人名列表。现在我想保证同名的人不会出现在两个文件中,例如,
File1:
.
.
James
James
Kobe
File2:
Kobe
Nash
Nash
.
.我要做的是
File1:
.
.
James
James
Kobe
Kobe
File2:
Nash
Nash
.
.在此之前,我使用sed手动完成此操作。现在我想写一个bash脚本来自动化这个过程,但是不熟悉bash..有什么帮助吗?怎么做?
发布于 2013-02-21 07:06:20
您需要将“当前”文件的最后一行与“下一步”文件的第一行进行比较。我假设您的文件名为"File1,File2,... FileN“。这是未经测试的。
n=1
while true; do
current=File$n
next=File$((++n))
if [[ ! -f $next ]]; then
break
fi
last=$(tail -1 "$current")
first=$(head -1 "$next")
while [[ $last == $first ]]; do
echo "$last" >> "$current" # append the name to the end of the current
sed -i 1d "$next" # remove the first line of the next file
first=$(head -1 "$next")
done
done这可能有点慢,因为您可能会重复地从下一个文件中删除一行。这可能会更快一些:同样,未经测试。
n=1
while true; do
current=File$n
next=File$((++n))
if [[ ! -f $next ]]; then
break
fi
last=$(tail -1 "$current")
first=$(head -1 "$next")
num=$(awk -v line="$last" -v N=0 '$0 == line {N++; next} {print N; exit}' "$next")
if (( num > 0 )); then
for (( i=1; i<=num; i++ )); do
echo "$last" >> "$current"
done
sed -i "1,$Nd" "$next"
fi
donehttps://stackoverflow.com/questions/14990520
复制相似问题