I am using grep command to take the required information from a file . I am using two grep statements like the below
XXXX='grep XXXX FILE A|sort|uniq|wc -l'
grep YYYY FILE A|uniq| > FILE B
Now the file is being traversed twice . But I just want to know, if I will be able to do these two steps in a single file traversal i.e I want to know if I could use something similar to egrep where I can grep for two strings and one string I will use it for stroring in a variable and output of another string into a file.
You can use the following code. Here we search for lines containing XXXX or YYYY in all file for only once and store the resulting lines to an array. Then we use elements of this array to select the lines containing XXXX and the lines containing YYYY.
filtered=`grep -E '(XXXX|YYYY)' FILE A`
XXXX=`for line in ${filtered[@]}; do echo $line; done | grep XXXX | sort | uniq | wc -l`
for line in ${filtered[@]}; do echo $line; done | grep YYYY | uniq > FILE B
So the file is not traversed twice!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With