BASH: rearrange lines in a file by line number & print in that order
Here's what I've tried with sed and here's what I'm getting.
From this list in a file called "baseball" Code:
Bats Code:
sed -n -e '1p;' -e '3p;' baseball Code:
Bats Code:
sed -n '2p; 4p; 1p' baseball Code:
Bats I'm thinking that because sed processes things in a stream (hence the name), and can find and return single lines, line pairs and ranges, it can't do anything as fancy as return many lines by their line number in any order that "goes against the stream." So what does do this? Or better, what would be a better way of reading in lines like the ones in baseball, and returning them in a "custom" order? BZT |
You can do something like this:
Code:
# Load the file into an array |
That almost works.
I added the word "Catchers" to the data file, and tried to use it to print every line in an arbitrary order Code:
mapfile -t someArray <baseball Code:
Catchers Quote:
Code:
mapfile -t cuteAussies <girls-image07.txt Quote:
Why should that be? Could the source data text file be corrupt, or is there another possibility? BZT |
The index is zero-based by default, and for lines with embedded spaces, you don't want the '-t' option (it would help to read the bash man page).
|
Yes, sed operates sequentially from start to finish. It reads in one line at a time and attempts to apply all the given expressions to them. So the output of the OP examples will always be in the order that they appear in the file.
|
Quote:
I'll try that. BZT |
Yeah, its historical.
Basically way back (1970 - ish), after a couple of attempts in various langs, Unix was re-written in C, and C arrays begin at zero because they are defined as mem_address + offset. Most tools/langs developed on *nix follow the same pattern. |
You could do the same process as mapfile / for loop with awk. Simply save all the data and then print the order you like.
If you use NR as the index you will also be able to use 1 to 6 for the line numbers. |
All times are GMT -5. The time now is 09:55 AM. |