Sorting and removing duplicate words in a line Sorting and removing duplicate words in a line bash bash

Sorting and removing duplicate words in a line


This works for me:

$ echo "zebra ant spider spider ant zebra ant" | xargs -n1 | sort -u | xargsant spider zebra

You can transform a list of words in a single row to a single column with xargs -n1 , use sort -u and transform back to a single row with xargs.


The shell was built to parse [:blank:] seperated word lists already. Therefore the use of xargs is completely redundant. The "unique" stuff can be done but its just easier to use sort.

echo $(printf '%s\n' zebra ant spider spider ant zebra ant | sort -u)


Use tr to change spaces to new lines, then sort, and finally change new lines back to spaces.

echo $(tr ' ' '\n' <<< "zebra ant spider spider ant zebra ant" | sort -u)