2

I have a file, its delimiter is "|||".

abc|||123|||999|||5|||Just for you | Jim|||20
cef|||7|||210|||6|||Go away | R&B|||30
mmm|||89|||320|||16|||Traveling Light|George Winston|||21

The delimiter "|||" can't be replace with "|" or "||", because data itself may contain "|" or "||".

Could someone tell me how to sort column 2 with delimiter "|||" ?

The following method fails:

sort -t$'|||' -nrk2 a.txt > b.txt
sort: multi-character tab `|||'

Thank you!

3
  • you could swap the columns and then use sort -n for the whole file without specifying a delimiter Commented Apr 19, 2017 at 6:43
  • @m13r You method doesn't work. The above a.txt is just a simple example. Real file contains many digital columns, and I must sort at least 2 digital columns, just like sort -t$'|||' -nrk2 -k3,rn -k4,rn a.txt > b.txt Commented Apr 19, 2017 at 11:19
  • When you say that it fails, what happens? Does sort fail to run, or does it just produce incorrect output? If it fails to run, what error message do you get? If the output is incorrect, what output do you get? Show an example of the output you get, and what you expect. Commented Apr 19, 2017 at 14:51

1 Answer 1

1

You could change the delimiter to | then sort it with sort and then change everything back:

# change | to __BAR__ writing the result to b.txt
sed 's@\([^|]\)|\([^|]\)@\1__BAR__\2@g' a.txt > b.txt
# change ||| to | in b.txt
sed -i 's@|||@|@g' b.txt

# do sorting with | delimiter writing the result to c.txt
sort -t$'|' -nrk2 -k3,rn -k4,rn b.txt > c.txt 

# change everything back in c.txt:
# | to |||
sed -i 's@|@|||@g' c.txt
# __BAR__ to |
sed -i 's@__BAR__@|@g' c.txt
Sign up to request clarification or add additional context in comments.

1 Comment

I bet this works for most folks, but my problem is that I'm using a multi-character delimiter in the first place because that's the only way to avoid confusing a delimiter content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.