在shell脚本中排序问题

时间:2019-05-20 08:38:42

标签: shell

如何在示例下面进行排序

输入:

n4Apple0.1banana
n1Apple0.4banana
n0Apple0.0banana
n2Apple0.3banana

输出:

n0Apple0.0banana
n4Apple0.1banana
n2Apple0.3banana
n1Apple0.4banana

1 个答案:

答案 0 :(得分:0)

尝试一下:

#!/bin/bash
data="YourDataFile"
tmpfile=$(mktemp)
sed 's/\(.*\([01]\.[0-9]*\).*\)/\2\1/' "$data" | sort -n > "$tmpfile"
sed 's/^...//' "$tmpfile" > "$data"
rm "$tmpfile"

说明

# get float from input an insert it at the front
sed 's/\(.*\([01]\.[0-9]*\).*\)/\2\1/' "$data"

0.1n4Apple0.1banana
0.4n1Apple0.4banana
0.0n0Apple0.0banana
0.3n2Apple0.3banana

# sort numeric and write into tmpfile
sort -n > "$tmpfile"

0.0n0Apple0.0banana
0.1n4Apple0.1banana
0.3n2Apple0.3banana
0.4n1Apple0.4banana

# extract float from the front an save it in your datafile
sed 's/^...//' "$tmpfile" > "$data"

n0Apple0.0banana
n4Apple0.1banana
n2Apple0.3banana
n1Apple0.4banana

# remove tmpfile