Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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 am a newbie in bash scripting and I want to ask if it is possible by using grep?

share|improve this question
    
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 yesterday

4 Answers 4

up vote 4 down vote accepted

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

share|improve this answer
    
Thanks! it is ok for my case –  Mitsos yesterday

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
share|improve this answer
    
this will match 01234 too, check my answer.. –  heemayl yesterday

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
share|improve this answer

try

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

where

  • condition with NR==1 to keep header line.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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