How do we sort input not separated by newlines?

Question

We are introduced to the sort function here. Can we use sort for sorting input not separated by newlines?

Answer

Though the function sort only works to sort input separated by newlines, just as we have been able to chain together simple command line functions to accomplish complex tasks, we can do the same to sort input not separated by newlines. In order to do this, we will need to replace the symbols separating the input we would like to sort by newlines. To accomplish this, we can use the sed command (which we also learn about in this section). For instance, if our input, in.txt, is separated by spaces instead of newlines, we can sort the file by

sed -e "s/ /\n/g" in.txt | sort
10 Likes

Hello, @zjedwin!

Thank you a lot for your explanation. I understand the sed function and what it does. The things written in red however, are a bit unfamiliar to me. Is this some sort of regular expression -RegEx-? Can you, please, let me know what they mean?

Thank you & again, sorry to bother!
Alex

you can do:

man sed

which is the manual, which contains the information needed:

s/regexp/replacement/
Attempt to match regexp against the pattern space. If success‐
ful, replace that portion matched with replacement. The
replacement may contain the special character & to refer to that
portion of the pattern space which matched, and the special
escapes \1 through \9 to refer to the corresponding matching
sub-expressions in the regexp.

so the s means subtitle
/ is a delimiter
is the regular expression, which is simple in this case, its only a space
\n is new line, so all spaces are replace by new lines.
g means global, without the global flag only the first occurrence in each line is replaced.

3 Likes

Whoaa! Thank you a lot, @stetim94! :smiley: This makes so much sense. I was looking on the internet also & somehow managed to understand portions of it. You confirming this made everything super clear & gave me a lot more support and made trust what I have learnt. I was about to finish the next challenge and a the last step found this:

Basically, is use sed to:

  • S - substitute
  • / - delimiter
  • loss - all instances of the word ‘loss’ with
  • ‘win’
  • g - apply those globally.
1 Like