Is it possible to grep for two files and assign their names to two separate variables with for loop? I am doing the below currently:
if [ $FLAG = 0 ]
then
for fname in $( cd $dirA ; ls -tr | grep "^Ucountry_file$")
do
InFile=$dirA/$fname
OutFile=$dirB/$fname.processed
:
:
:
more lines of code
done
fi
fname in the for loop here holds the name of the Ucountry_file. Likewise, in the same $dirA, there is another file called Rcountry_file. I want to grep for that as well and assign to another variable using the same for loop. Can it be done?
Have I got this right, or have I missed the point?
The first option specifies the name you are after with a | to make it an 'or' comparison. The second option searches for a line starting with either U or R, following by country_file then the end of the line.
I hope that this helps, but let me know if I'm miles off track. I must admit I don't know where $dirB comes from in your code.
In general, instead of cramming thousands of filenames in backticks into a for, you should be doing command | command | while read because for has some problems here, like a limit on number of files, and potential accidental splitting on spaces instead of lines.
Anyway. You can do two greps separately, saving one into a file, then opening the file to read later...
command1 > /tmp/$$
exec 5</tmp/$$ # Open file into FD 5
rm /tmp/$$ # Delete file (Will stay readable until you close it )
command2 | while read LINE1
do
read LINE2 <&5
echo "LINE1 $LINE1 LINE2 $LINE2"
done
exec 5<&- # Close file
I must be missing something basic here. I'll go a small step beyond where RudiC went. I don't see the need for a for loop at all. If I'm reading the code correctly the commands in the for loop will be executed once if $dirA/Ucountry_file exists and will not be executed if that file does not exist. If I understand the question correctly, I think the following would be a much simpler way to handle it:
ft=country_file
fname=U$ft
if [ $FLAG = 0 ]
then
if [ -e "$dirA/R$ft ] && [ -e "$dirA/$fname" ]
then
InFile=$dirA/$fname
InFile2=$dirA/R$ft
OutFile=$dirB/$fname.processed
:
:
:
more lines of code
else ... do ... if Rcountry_file or Ucountry_file is missing ...
fi
fi
In the then part of the inner if, $fname will be what it was in the original for loop, $InFile will be as it was in the original for loop (a pathname for the Ucountry_file in $dirA) and $InFile2 will be a pathname for the Rcountry_file in $dirA.