Selecting lines according to position in a file
Have: a file called numbs consisting of positive integers, one per line ...
Code:
3 Have: a file called words consisting of text ... Code:
one The desired output is a file consisting of lines selected from words according to the numbers in numbs ... Code:
three These are failed attempts: Code:
sed 's/$/p/' $Numbs >$Work Code:
awk 'FNR==NR{a[$0];next}FNR in a' $Numbs $Words >$OutFile |
Is this what you are looking for (bash only solution):
Code:
#!/bin/bash |
Quote:
Daniel B. Martin |
From a technical point of view those are 2 loops, but....
The way they are implemented in my solution they work like sed or awk (read each file once, one line after another). If that is considered a loop then both sed and awk cannot be used either ;) |
Quote:
|
Let's start with obvious loop:
Code:
while read n ; do sed -n ${n}p words ; done < numbs Code:
xargs -I{} sed -n {}p words < numbs awk solution (equivalent to druuna's bash solution): Code:
awk 'NR==FNR { w[NR] = $0; next } { print w[$0] }' words numbs |
Quote:
Daniel B. Martin |
Quote:
|
Quote:
For the sake of learning: Please explain why my attempt with sed ... Code:
sed 's/$/p/' $Numbs >$Work Code:
two Can my sed be changed to make it work, and still be loop-less? Daniel B. Martin |
Hi, Daniel.
Your sed solution does not work, because on the second line you execute sed script $Work on each line of file $Words. For example, you apply script "3p;6p;2p;8p;8p;2p;8p;" to an input line number 2. The script contains '2p' two times, so sed prints second line two times. EDIT: Wow, it's my 600-th post here :) |
Quote:
Code:
sed = words | sed '1~2s:^.*$:/&/i\\:' | sed -nf - numbs |
Hi again!
Maybe try another tool?: Code:
$ ed words < nums This works, because ed treats numbers on stdin as line addresses to print. Read info ed for more info. |
Quote:
Code:
Maybe try another tool?: Daniel B. Martin |
Quote:
|
Hi.
Quote:
Quote:
|
All times are GMT -5. The time now is 12:16 AM. |