Hi I've tried many solutions to similar questions and none have seemed to work for me. I have a text file where each line has an undefined length of numbers after the string " length_ ". How can I select out all the lines where that number is equal to or greater than 5000? This has been the cleanest looking code attempt I’ve tried so far, but it still just produces an empty file (even though file1 definitely contains lines with numbers greater than 5000)

grep --regexp="length_\"[5-9][0-9]\{3,\}\"" file1.txt > file2.txt

example info within input text file:

desired example info within output text file:

  • Please post a few lines from a sample input file, and make up a corresponding results file (i.e. show us the exact input you have and the exact output you expect). – tniles Jul 12 '16 at 16:02
  • Do you want greater than or less than? – Jeff Schaller Jul 12 '16 at 16:04
  • Given that your actual input file doesn't start with "length_", I updated my answer accordingly. – Jeff Schaller Jul 12 '16 at 17:25

Here's one way, using awk, to print lines from a file that contain a number after the string "length_" that is less than or equal to 5000:

awk '{sub("length_", "", $0); if ($0 <= 5000) { print "length_"$0 } }' input

It simply tells awk to strip off the "length_" string, then compare the remaining part of the line to 5000; if it's less than or equal to 5000, print "length_" and the remainder of the line. Your Q's subject line says (at the time) "greater than 5000", so if that's the actual desire, simply change the comparison in awk:

awk '{sub("length_", "", $0); if ($0 > 5000) { print "length_"$0 } }' input

Given the actual file format, the awk command can be simplified considerably:

awk -F_ '$4 > 5000' input


awk -F_ '$4 <= 5000' input

by telling awk to split the fields based on underscores, then comparing the fourth field to 5000. If the comparison is true, then (by default) print.

  • This second solution using the underscore as a field separator and then filtering the column containing the numbers for greater than 5000 works perfectly. nifty solution. – Giles Jul 12 '16 at 17:43
grep -E '_length_([5-9][0-9]{3}|[0-9]{5,})_' file1.txt > file2.txt

outputs lines containing:

  • _length_ followed by either:
    • 5 - 9 and 3 more digits (5000-9999) or
    • 5 or more digits (10000+)
  • followed by _.

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.