0

I have a file months.txt with the following text:

JAN, MAR, DEC, FEB, JUN, APR

In bash I write the following line of code:

cat months.txt | sort -M

I assumed that this would output the text file, sorted by month. However the output is not sorted. Am I using sort incorrectly?

Jakeimo
  • 71
  • 6

3 Answers3

2

sort sorts lines of text, and you've only given it one.

If your file looked like this:

JAN
MAR
DEC
FEB
JUN
APR

... you'd get the result you expect.

Incidentally, your command is a useless use of cat: the command

sort -M months.txt

does exactly the same thing.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
1

You need to turn the comma-separated list into separate lines, sort it, and then convert it back:

tr ',' '\n' < months.txt | sort -M | awk 'NR > 1 { printf(",") } {printf("%s", $0)} END { print "" }'
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Another take:

tr -s ', ' '\n\n' < months.txt | sort -M | paste -sd,
JAN,FEB,MAR,APR,JUN,DEC

No whitespace in the output.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352