'What is the "\0" escape and xargs 0n1 do here?
itsmejitu@itsmejitu:~$ numbers=(47 -78 12 45 6)
itsmejitu@itsmejitu:~$ printf "%d \n" ${numbers[@]} | sort -n
-78
6
12
45
47
itsmejitu@itsmejitu:~$ declare -a letters
itsmejitu@itsmejitu:~$ letters=(a c e z l s q a d c v)
itsmejitu@itsmejitu:~$ printf "%s \0" ${letters[@]} | sort -z | xargs -0n1
a
a
c
c
d
e
l
q
s
v
z
itsmejitu@itsmejitu:~$ printf "%s \n" ${letters[@]} | sort -z | xargs -0n1
a
c
e
z
l
s
q
a
d
c
v
Sorting integers is straightforward I tried to do sorting of letters in bash. Couldn't do it, So my friend sent me this. He couldn't explain though. I looked through printf, xargs manuals. But the terms used there is beyond my understanding(Not a CS student). Is there any simpler way to understand this? thanks!!
Solution 1:[1]
In the first example, sort sees 5 different numbers separated by line feeds.
In the second example, sort and xargs see 11 different two-character strings (each has a trailing space) separated by null characters.
In the third example, sort and xargs see a single string (containing embedded line feeds and spaces) "separated" by a null character.
It might help to pipe the output of printf through hexdump -C or od to see what sort sees in each case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chepner |
