0

I am trying to sort the rows of a text file in Unix Korn shell.

Sample File:

3|"Apple"|"iphoneX"|"This is the latest phone."|"California"
2|"Samsung"|"s9"|"This phone isn't so good.
It hangs for no reason when old."|"Texas"
1|"OnePlus"|"5t"|"This is a good android phone."|"Arizona"

Expected O/P:

1|"OnePlus"|"5t"|"This is a good android phone."|"Arizona"
2|"Samsung"|"s9"|"This phone isn't so good.
It hangs for no reason when old."|"Texas"
3|"Apple"|"iphoneX"|"This is the latest phone."|"California"

I tried this:

${FileDir}${INPUT_FILE} |sort -t '|' -k ${SORT_COL_ORD} >>${FileDir}${SORT_OUTPUT_FILE}

But it's failing due to a new line feed in row 2. And my O/P is something like this :

1|"OnePlus"|"5t"|"This is a good android phone."|"Arizona"
2|"Samsung"|"s9"|"This phone isn't so good.
3|"Apple"|"iphoneX"|"This is the latest phone."|"California"
It hangs for no reason when old."|"Texas"

I am passing an arg to sort on col 1 (Ids).What am I missing here?

4
  • 3
    sort sorts lines. You're going to need to transform the input so that single logical lines are on a single physical line. You might do that by replacing any occurrences of backslash with double backslash, any occurrences of newline in a logical line with \n, and then sort the data appropriately, and finally undo the transform. It is at least as much fiddly as difficult. Commented Apr 12, 2018 at 0:48
  • if you run a search for 'sort multiple lines' you should get some hits that can help, eg: How to sort multiple lines in bash , Sort text files with multiple lines as a row Commented Apr 12, 2018 at 13:22
  • The hard part in this situation is determining which lines need to be combined. How hard that is to manage depends on how general a solution you need. What you've got is a version of CSV — character separated values in this context, rather than comma separated values. Are all non-numeric fields quoted? It looks like it, whether the quotes are necessary or not. Supposing one of the fields said It is wonderful except it has no "|" (pipe) character — how would that be encoded? At this point, something like Perl with the Text::CSV module(s) starts to be beneficial. Perl can sort, too. Commented Apr 12, 2018 at 17:22
  • Thanks for the suggestion guys. I am not sure if it's a proper solution but i managed to solve my case here. I replaced the newline with a named string, sorted the files and then replaced with a newline. awk '{z=gsub("\"","\""); if ( ( z%2) && (nl==0)) { printf $0"WWNewLineWW" ; nl=1} else {print ; nl=0}}' Commented Apr 13, 2018 at 20:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.