Yesterday I had to select some raws (1, 5, 9, ….) from a text file.

This has been a hard job because I was trying to solve the wrong problem……

Really, before coding you should analyze deeply your problem and then you should think which tool you need to use.

However, come on and see my experiments:

First of all we need a test file, I'll use the following:

$ cat test.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

 

On the internet I've seen a simple awk script that is able to extract even lines from a file:

 awk 'NR % 2 == 0' test.txt

So I changed this line to work with odd lines

$ awk 'NR % 2 != 0' test.txt > test1.txt
$ cat test1.txt
 
1
3
5
7
9
11
13
15
17
19

then I ran the command another time

 

$ awk.exe 'NR % 2 != 0' test1.txt > test2.txt
$ cat test2.txt
1
5
9
13
17

So I obtained the wanted result.

Instead of searching for odd lines I have had to search directly for my need. It was simple and fast, the modulo of the NR and 4 must be 1 so the following command works fine:

 

$ awk 'NR %4 == 1 ' test.txt > test3.txt
$ cat test3.txt
1
5
9
13
17

For those who loves sed and hate awk I have another command:

 

$ sed -n '1,${p;n;n;n}' test.txt  > test4.txt
$ cat test4.txt
1
5
9
13
17

 

If you found useful this article, please share it using the social buttons below. Thank you in advance.

Gg1