Reputation: 13
I am trying to return data which occurs on specific lines in one file, and use those lines to return the data from another file on those same lines. I have been looking through the notes online here, and have found something i thought would work. However i am getting an error currently. any suggestions?
file1
has the values 1 2 3
file2
has the values three four five
so the output should be three
#!/bin/bash
awk '/one/ {print NR}' file1>fileonehold
filename="fileonehold"
while read -r line
do
sed -n ${line}p file2 >> file2hold
done < "$fileonehold"
Upvotes: 1
Views: 32
Reputation: 44063
If I understand what you're trying to do correctly, then the most straightforward way is to use awk:
awk -v pattern="one" 'NR == FNR && $0 ~ pattern { a[FNR] = 1 } NR != FNR && a[FNR]' file1 file2
This works as follows: -v pattern="one"
makes known to awk a variable named pattern
whose value is one
. Then the code is
NR == FNR && $0 ~ pattern { # if we're still processing the first file (file1),
# and if the current line matches the pattern
a[FNR] = 1 # remember that line number.
}
NR != FNR && a[FNR] # if we're not processing the first file and the
# current line number is a remembered one, print.
The core trick here is the condition NR == FNR
(and NR != FNR
). NR
is the number of records (lines, by default) processed so far, FNR
is the number of records processed so far from the current file. These are equal when processing the first file from the command line but not afterwards.1
Apart from that: the condition NR != FNR && a[FNR]
does not have an associated action, so the default action (printing) is performed if it is true. a[FNR]
is true only for marked lines because the default value (an empty string) is considered false and 1
(the marker value) is considered true by awk.
1 unless the first file is empty, in which case the code will still not print anything.
Upvotes: 1