有没有一个很好的bash单行程序来将文件中的字符串映射到一个唯一的数字?
例如,
a
a
b
b
c
c
应转换为
1
1
2
2
3
3
我目前正在用C++实现它,但是bash一行程序将会很棒。
发布于 2010-09-29 16:55:16
awk '{if (!($0 in ids)) ids[$0] = ++i; print ids[$0]}'
这将维护一个名为ids
的关联数组。每当它找到一个新的字符串时,它就会给它分配一个一元递增的id ++i
。
示例:
jkugelman$ echo $'a\nb\nc\na\nb\nc' | awk '{if (!($0 in ids)) ids[$0] = ++i; print ids[$0]}'
1
2
3
1
2
3
发布于 2010-09-29 17:05:41
这里的awk解决方案很好,但这里是使用纯bash (>=4)的相同方法。
declare -A stringmap
counter=0
while read string < INPUTFILE; do
if [[ -z ${stringmap[$string]} ]]; then
let counter+=1
stringmap[$string]=$counter
fi
done
for string in "${!stringmap[@]}"; do
printf "%d -> %s\n" "${stringmap[$string]}" "$string"
done
发布于 2010-09-29 16:57:15
awk 'BEGIN { num = 0; }
{
if ($0 in seen) {
print seen[$0];
} else {
seen[$0] = ++num;
print num;
}
}' [file]
(当然,不只是一行。)
https://stackoverflow.com/questions/3823878
复制