Issue
I can find sed solutions to delete all lines in a text file starting with a '1' as well as solutions to delete every other line of all the lines in the text file but I want to combine the two.. of all the lines starting with '1' delete every other one of them and keep the other lines that do not start with a 1.
So if I have a text file:
1, 1
1, 2
2, 3
3, 4
4, 5
2, 6
1, 7
3, 8
1, 9
4, 10
I want the output to be:
1, 1
2, 3
3, 4
4, 5
2, 6
1, 7
3, 8
4, 10
Solution
You could do this in awk:
awk -F, '!($1 == 1 && n++ % 2)' file
-F,
means use comma as the field separator, so the two numbers on each line will be the variables $1
and $2
.
awk will print the line if the last thing it evaluates is true. The !
negates the contents of the parentheses, so in order to print, the contents must be false.
If the first field isn't 1
, short-circuiting takes place, as (false && anything)
will always be false. This means that the second half after the &&
will not be evaluated.
If $1 == 1
, then the second half is evaluated. As n
is being used for the first time in a numeric context, it will assume the value 0
. The modulo operation n % 2
will return 0
(false) for even numbers and 1
(true) for odd numbers. Using the increment n++
means that the result will alternate between true and false.
You may prefer the reverse logic, which would be:
awk -F, '$1 != 1 || ++n % 2' file
The ||
is also short-circuiting, so if the first value isn't 1
then the line gets printed. Otherwise, the second half is evaluated. This time, the increment goes before the n
so that the first value of n
is 1
, making the expression evaluate to true.
Either way, the output is:
1, 1
2, 3
3, 4
4, 5
2, 6
1, 7
3, 8
4, 10
Answered By - Tom Fenech Answer Checked By - Marie Seifert (WPSolving Admin)