4

I have a file with multiple lines which looks like that :

brand,model,inches,price

dell       xps      13    9000     
macbook    pro      13    13000
asus       zenbook  13    10500

I want to delete the lines where the price is more than 10000. I want to ask if it is possible by using grep?

  • May the last field look like 08000 or 8999.90 or 1e8 or is it limited to well-behaved (without leading 0) decimal integer numbers? – Stéphane Chazelas Sep 16 '15 at 14:43
5

You can use the following to get the lines where price is greater than 10000 :

$ grep -E '.* [0]*[1-9][0-9]{4,}$' file.txt 
macbook    pro      13    13000
asus       zenbook  13    10500

If you want to remove those lines add -v :

$ grep -vE '.* [0]*[1-9][0-9]{4,}$' file.txt 
dell       xps      13    9000     
  • .* will match all characters upto the last column containing prices

  • [1-9] will match the first digit of the price

  • [0-9]{4,}$ will match 4 or more digits after the first digit so we have a total of five digits meaning 10000 or greater

4

It's possible, but grep uses regular expressions that operate on strings, not numbers.

grep -v '[0-9]\{5\}$' input.txt

-v removes the matching lines. [0-9] matches any digit, \{n\} means the preceding thing is repeated n times (5 times in this case, i.e. 10000 and more). $ matches the line end.

awk can compare numbers, so it's more suitable for the job:

awk '$4<10000{print}' input.txt

or Perl:

perl -ane 'print if $F[-1] < 10000' input.txt
  • this will match 01234 too, check my answer.. – heemayl Sep 16 '15 at 14:31
  • I don't know if it's correct to say that grep -v deletes the matching lines. It simply inverts the matching so that it selects all non-matching lines. – Zach Conn Jul 20 '16 at 21:20
2

Given your sample input:

$ cat /tmp/foo
dell       xps      13    9000
macbook    pro      13    13000
asus       zenbook  13    10500

You can use awk:

$ awk '{ if ($4 <= 10000) print; }' /tmp/foo
dell       xps      13    9000
2

try

cp input.txt original.txt
awk 'NR==1 || $4 < 10000 ' original.txt > input.txt

where

  • condition with NR==1 to keep header line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.