Tim Bellis
Tim Bellis

Reputation: 1657

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

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.

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

I can use either bash or ksh.

Upvotes: 1

Views: 1979

Answers (3)

doubleDown
doubleDown

Reputation: 8408

In awk:

for num in "$@"; do
    awk "NF==$num" file
done

Bash-only (don't need to reset IFS if you are putting this in a script):

IFS=$'\n'
lines=( $(<file) )
for num in "$@"; do
    echo lines[num-1]
done

Upvotes: 1

choroba
choroba

Reputation: 242038

You can use sed:

for num in $input ; do
    sed $num'!d' file
done

Upvotes: 4

Barmar
Barmar

Reputation: 782099

Here's a perl solution:

#!/usr/bin/perl -w
my @lines = <STDIN>; # Read stdin into an array
foreach my $linenum (@ARGV) { # Get the new order from argument list
  print $lines[$linenum-1];
}

Run the script as:

./scriptname 2 1 3 4 < inputfile

Upvotes: 2

Related Questions