0

The answers in Sorting lines from longest to shortest provide various ways to sort a file's lines from longest to shortest.

I need to temporarily sort a file from longest to shortest, to give some time for a BASH script to perform some operations to edit various content, but then to restore the file to its original order after the BASH script has finished.

How can I first sort a file from longest to shortest, but then be able to restore the order later?

Community
  • 1
  • 1
Village
  • 22,513
  • 46
  • 122
  • 163

2 Answers2

4

Done by enhancing your linked answer by these steps:

  1. Prepend a length and line number to the front of each line, sort by length, cut length (just like in linked answer)

    perl -ne 'print length($_)." $. $_"' file.txt | sort -r -n | cut -d ' ' -f 2- > newfile.txt
    
  2. Do your bash translation (ignoring first number on each line)

    If for some reason you can't do your amorphous translation with the number prefixes, then split the numbers into a separate file and merge them back in afterwords.

  3. Sort by line number and then cut off line number to restore file to previous state.

    sort -n newfile.txt | cut -d ' ' -f 2- > file.txt
    
Community
  • 1
  • 1
Miller
  • 34,962
  • 4
  • 39
  • 60
2

Something like this to store the original line order in a separate file might be what you need:

awk -v OFS='\t' '{print length($0), NR, $0}' infile |
sort -k1rn -k2n |
tee order.txt |
cut -f3- > sorted.txt

do stuff with sorted.txt then

cut -f2 order.txt |
paste - sorted.txt |
sort -n |
cut -f2- > outfile

You don't say what you want done with lines that are the same length as each other but the above will preserve the order from the original file in that case. If that's not what you want, play with the sort -rn commands, modifying the -ks as necessary.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185