User Tools

Site Tools


linux:scripts:translate_to_order_comma_separated_values

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

linux:scripts:translate_to_order_comma_separated_values [2011/08/17 13:09] (current)
amon created
Line 1: Line 1:
 +I just had an interesting thing to solve. I had a comma separated list of text strings that I wanted to sort alphabetically. It was infarct a list of ant targets. ​
 +
 +E.g.
 +<​code>​
 +item1,​item3,​item2,​item4
 +</​code>​
 +
 +The steps I thought up were quite simple:
 +  - Convert to a list (separate values by line breaks) in test.txt
 +  - Sort the list
 +  - Convert back to comma separated
 +
 +====== Using translate ======
 +''​tr'',​ translate (its an interesting and useful unix tool) allows for simple character substitution (amongst many other things).
 +<code bash>
 +cat test.txt | tr ','​ '​\n'​ | sort | uniq |  tr '​\n'​ ','​
 +</​code>​
 +
 +  - ''​cat''​ (output file).
 +  - ''​tr''​ translate - (in this case replace a comma ","​ with a new line "​\n"​).
 +  - ''​sort''​ the output list alphabetically.
 +  - ''​uniq''​ remove duplicates (only works on a sorted list).
 +  - ''​tr''​ translate - (in this case replace a new line "​\n"​ with a comma ","​).
 +
 +While ''​tr''​ [[http://​unixhelp.ed.ac.uk/​CGI/​man-cgi?​tr+1]] has lots of specific uses and this isn't exactly what it was designed for. The syntax on an individual character replace is simpler than ''​sed''​.
  
linux/scripts/translate_to_order_comma_separated_values.txt · Last modified: 2011/08/17 13:09 by amon