0
votes

In my shell script, one of the variable contains set of lines. I have a requirement to get the two lines info at single iteration in which my awk needs it.

var contains:

12 abc
32 cdg
9 dfk
98 nhf
43 uyr
5 ytp

Here, In a loop I need line1, line2[i.e 12 abc \n 32 cdg] content and next iteration needs line2, line3 [32 cdg \n 9 dfk] and so on..

I tried to achieve by

while IFS= read -r line
do
count=`echo ${line} | awk -F" " '{print $1}'`
id=`echo ${line} | awk -F" " '{print $2}'`
read line
next_id=`echo ${line} | awk -F" " '{print $2}'`
echo ${count}
echo ${id}
echo ${next_id}

## Here, I have some other logic of awk..
done <<< "$var"

It's reading line1, line2 at first iteration. At second iteration it's reading line3, line4. But, I required to read line2, line3 at second iteration. Can anyone please sort out my requirement.

Thanks in advance..

2
What is the expected output?M. Nejat Aydin

2 Answers

1
votes

Don't mix a shell script spawing 3 separate subshells for awk per-iteration when a single call to awk will do. It will be orders of magnitude faster for large input files.

You can group the messages as desired, just by saving the first line in a variable, skipping to the next record and then printing the line in the variable and the current record through the end of the file. For example, with your lines in the file named lines, you could do:

awk 'FNR==1 {line=$0; next} {print line"\n"$0"\n"; line=$0}' lines

Example Use/Output

$ awk 'FNR==1 {line=$0; next} {print line"\n"$0"\n"; line=$0}' lines
12 abc
32 cdg

32 cdg
9 dfk

9 dfk
98 nhf

98 nhf
43 uyr

43 uyr
5 ytp

(the additional line-break was simply included to show separation, the output format can be changed as desired)

You can add a counter if desired and output the count via the END rule.

0
votes

The solution depends on what you want to do with the two lines.
My first thought was something like

sed '2,$ s/.*/&\n&/' <<< "${yourvar}"

But this won't help much when you must process two lines (I think | xargs -L2 won't help).
When you want them in a loop, try

while IFS= read -r line; do
   if [ -n "${lastline}" ]; then
      echo "Processing lines starting with ${lastline:0:2} and ${line:0:2}"
   fi
   lastline="${line}"
done <<< "${yourvar}"