我有一个巨大的文本文件,每行都有已排序的数字。我想使用sed或awk将其转换为大块范围。 例如:
1
2
3
5
6
9
11
12
应转化为:
1-3
5-6
9
11-12
使用sed进行此类转换是否合理?
答案 0 :(得分:1)
这是一个awk
解决方案:
awk 'NR==1 {printf $0} p+1!=$0 {printf "-"p"\n"$0} {p=$0} END {print "-"$0}' file
1-3
5-6
9-9
11-12
这假设所有行都有数字,并且每行都会增加。
使用printf
awk 'NR==1 {printf "%s",$0} p+1!=$0 {printf "-%s\n%s",p,$0} {p=$0} END {print "-"$0}'
答案 1 :(得分:0)
Perl解决方案:
perl -lne 'sub out { print $first == $prev ? $first : "$first-$prev" } # Produce the output.
if ($_ != $prev+1 and defined $first) { # Current number not in seq.
out(); # Output the previous seq.
$first = $_; # Start a new one.
}
$prev = $_; # Remember the current number.
$first = $_ if !defined $first; # Initialize for the first line.
}{ out() # Output the last sequence.
' input.txt
答案 2 :(得分:0)
好的伙计们,bash解决方案:
A=`head -n1 data.txt`
B=$A
while read LINE
do
if [[ `expr $LINE - $B` != 1 ]]
then
if [[ "$A" != "$B" ]]
then
echo "-$B"
else
echo
fi
A=$LINE
echo -n "$A"
fi
B=$LINE
done < data.txt