newwave
newwave

Reputation: 85

How can I remove lines in which length of a field exceeds some threshold using awk or sed?

I have the file test.txt similar to that:

aa:bbbbbb:22.3
a:bb:33.2
a:bbbb:22.3
aaaa:bb:39.9


I know how to count and sort them like:

awk -F ':' '{print $2}' test.txt | awk '{print length($0),$0}' | sort -nr


Now I want to remove the 1st and 3rd lines from the file because the length of the second field (containing "b") in those lines is larger than 3. How can I do that using awk/sed? Thanks.

Upvotes: 0

Views: 2020

Answers (2)

captcha
captcha

Reputation: 3756

Code for :

sed '/.*:..:.*/!d' file

or more general:

sed '/.*:.\{2\}:.*/!d' file

Upvotes: 4

fedorqui
fedorqui

Reputation: 290075

With awk:

This will output the lines whose 2nd field is >3:

$ awk -F: 'length($2)>3' file
aa:bbbbbb:22.3
a:bbbb:22.3

To do the opposite:

$ awk -F: 'length($2)<=3' file
a:bb:33.2
aaaa:bb:39.9

Upvotes: 6

Related Questions