Reputation: 1657
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
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
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