Selecting lines based on position
I want to select lines based on their position (i.e. line number).
Sample of File1... Quote:
Quote:
Quote:
Daniel B. Martin |
Hi.
Code:
# save to select.awk Code:
$ awk -f select.awk numbers.txt file1.txt |
Can be a little simpler:
Code:
awk 'FNR == NR{nums[$0];next}FNR in nums' numbers.txt file1.txt |
Quote:
Quote:
|
Apparently your samples above contain a trailing blank space at the end of the last line (after Georgia and 7 respectively). Therefore the last number is not treated as such, but as a literal string of two characters.
A slight modification to the grail's code should reveal the arcane: Code:
awk 'FNR == NR{nums[$0+0];next}FNR in nums' numbers file |
Thanks for the fix colucix :) I often forget there can be other dodginess around ;)
|
Hi grail! :) That wasn't so obvious. I'd have never thought about that if I hadn't tried to copy/paste the sample input in a terminal.
|
@colucix: Since the key is a line number, and thus integer, wouldn't nums[int($1)] be cleaner?
BTW, I did not know that array element reference was enough to define it. The GNU Awk manual does mention it -- A reference to an element that does not exist automatically creates that array element, with the null string as its value -- and not as specific to GNU awk. I just hadn't encountered that before. Useful; thanks! |
Quote:
|
Quote:
1) Thank you to everyone who contributed ideas, code, corrections, and comments to this thread. It is SOLVED! 2) I use gnome-terminal to browse a file. In this instance I was tripped by trailing blanks which are invisible to the unaided eye. I'd like to use a browser which distinguishes white space with a colored dot or some such. Is there a user setting for gnome-terminal which does this? Is there a different utility which can do this? Daniel B. Martin |
The same technique can be done directly in bash too, Version 4's new mapfile built-in makes it particularly easy.
Code:
mapfile -t -O 1 states <file.txt For older bash versions, use a read loop to populate the array: Code:
while IFS= read -r line; do Code:
for i in 2 3 5 7; do Edit 2: Oh, but for just a simple list: Code:
sed -n "2p; 3p; 5p; 7p" file.txt |
All times are GMT -5. The time now is 06:52 AM. |