How do we sort input not separated by newlines?


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


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

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!

you can do:

man sed

which is the manual, which contains the information needed:

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.


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.

Why do we use the option ‘-e’? What does the option do? Can we also write the above statement like - ‘sed “s/ /\n /g” in.txt’ | sort’.

Same answer? have you checked man sed or sed --help to see what -e does?