How to process every other line in bash
awk, bash
Solution
If you're planning to do a simple `grep`, you can do away with the additional step and do the filtering within awk itself, e.g.:
awk 'NR % 2 {print} !(NR % 2) && /pattern/ {print}' file.fasta
However, if you intend to do a lot more then, as chepner already pointed out, you can indeed pipe from inside awk. For example:
awk 'NR % 2 {print} !(NR % 2) {print | "grep pattern | rev" }' file.fasta
That opens a pipe to the command `"grep pattern | rev"` (note the surrounding quotes) and redirects the print output to it. Do note that the output in this case may not be as you might expect; you will end up with all odd lines being output first followed by the output of the piped command (which consumes the even lines).
(In response to your comments) to count the number of chars in each even line, try:
awk 'NR % 2 {print} !(NR % 2) {print length($0)}' file.fasta
Problem
I would like to print odd lines (1,3,5,7..) without any change, but even lines (2,4,6,8) process with pipeline beginning with grep. I would like to write everything to new file (odd lines without any change and new values for even lines). I know how to print every other line in awk: ``` awk ' NR % 2 == 1 { print; } NR % 2 ==0 {print; }' file.fasta ``` However, for even lines, I dont want to use `{print; }` but I want to use my grep pipeline instead. An advice will be appreciated. Thanks a lot.