【发布时间】:2020-05-03 16:27:12
【问题描述】:
我有一个看起来像这样的文件:
dog
cat
dog
dog
fish
cat
我想在 Bash 中编写一些代码来使文件格式如下:
dog:1
cat:1
dog:2
dog:3
fish:1
cat:2
知道如何做到这一点吗?该文件非常大(> 30K 行),因此代码应该有点快。
我在想某种循环......
像这样:
while read line;
echo "$line" >> temp.txt
val=$(grep $line temp.txt)
echo "$val" >> temp2.txt
done < file.txt
然后paste -d ':' file1.txt temp2.txt
但是,我担心这会很慢,因为您要逐行进行。其他人怎么看?
【问题讨论】:
-
请展示你的尝试
-
刚刚更新了原来的问题!
-
是的,它会非常慢,并且由于部分匹配会产生不正确的值,并且它还有其他问题,例如它会破坏某些输入,会根据输入值和运行它的目录等。请参阅 why-is-using-a-shell-loop-to-process-text-considered-bad-practice。