How do I arbitrarily reorder lines in a text file using a Unix shell?

Posted by Tim Bellis on Stack Overflow See other posts from Stack Overflow or by Tim Bellis
Published on 2012-11-01T10:51:53Z Indexed on 2012/11/01 11:00 UTC
Read the original article Hit count: 158

Filed under:
|
|
|

I've got a text file with an arbitrary number of lines, e.g.:

one line
some other line
an additional line
one more here

I'd like to write a script to reorder those lines based on a given order. e.g.

  • An input of 2 1 3 4 would swap the first and second lines.
  • An input of 3 1 2 4 would put the 3rd line first, the 1st line second, the 2nd line third and keep the 4th line fourth.

I could hack something together, but I'm wondering if there's an elegant solution?

I can use either bash or ksh.

© Stack Overflow or respective owner

Related posts about bash

Related posts about shell