简体   繁体   English

重击然后排序

[英]Bash then sorting it

Hey guys so i have this sample data from uniq-c: 大家好,我从uniq-c获得了以下示例数据:

100 c.m milk
99 c.s milk
45 cat food
30 beef

desired output: 所需的输出:

beef,30
c.m milk,100
c.s milk,99
cat food,45

the thing i have tried are using: 我尝试过的东西正在使用:

awk -F " " '{print $2" " $3 " " $4 " " $5 "," $1}' stock.txt |sort>stock2.csv

i got : 我有 :

beef   ,30
cat food
  ,45
c.m milk
  ,100
c.s milk
  ,99

think its because some item doesn't have 2,3,4,5 and i still use " ", and the sort in unix doesn't prioritise dot first unlike sql. 认为这是因为某些项目没有2,3,4,5并且我仍然使用“”,并且unix中的排序不像sql那样优先点的优先级。 however i'm not too sure how to fix it 但是我不太确定如何解决它

i think you can solve it in bash using some easy commands, if the format of the file is as you posted it: 我认为您可以使用一些简单的命令在bash中解决它,如果文件的格式与您发布的格式相同:

prova.txt is your file. prova.txt是您的文件。

then do: 然后做:

cat prova.txt  | cut -d" " -f2,3 > first_col
cat prova.txt  | cut -d" " -f1 > second_col
paste -d "," first_col second_col | sort -u > output.csv
rm first_col second_col

in output.txt you have your desired output in CSV format! 在output.txt中,您具有CSV格式的所需输出!

EDIT: 编辑:

after reading and applying PesaThe comment, the code is way easier: 阅读并应用Pesa注释后,代码变得更简单:

paste -d, <(cut -d' ' -f2- prova.txt) <(cut -d' ' -f1 prova.txt) | sort -u > output.csv

To obtain your desired output you could sort first your current input and then try to swap the columns. 为了获得所需的输出,您可以先对当前输入进行sort ,然后尝试交换列。

Using awk , please give a try to this: 使用awk ,请尝试以下操作:

$ sort -k2 stock.txt | awk '{t=$1; sub($1 FS,""); print $0"," t}'

It will output: 它将输出:

beef,30
c.m milk,100
c.s milk,99
cat food,45

Combining additional information from this thread with awk , the following script is a possible solution: 从结合其他信息螺纹与awk ,下面的脚本是一个可能的解决方案:

awk ' { printf "%s", $2; if ($3) printf " %s", $3; printf ",%d\n", $1; } ' stock.txt | LC_ALL=C sort > stock2.csv

It works well in my case. 就我而言,它运作良好。 Nevertheless, I would prefer nbari's solution because it is shorter. 不过,我更喜欢nbari的解决方案,因为它的时间更短。

$ awk '{$0=$0","$1; sub(/^[^[:space:]]+[[:space:]]+/,"")} 1' file | LC_ALL=C sort
beef,30
c.m milk,100
c.s milk,99
cat food,45

You can use sed + sort : 您可以使用sed + sort

sed -E 's/^([^[:blank:]]+)[[:blank:]]+(.+)/\2,\1/' file | C_ALL=C sort

beef,30
c.m milk,100
c.s milk,99
cat food,45

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM