Skip to content

Instantly share code, notes, and snippets.

@xaviershay
Created December 19, 2011 00:27
Show Gist options
  • Save xaviershay/1494931 to your computer and use it in GitHub Desktop.
Save xaviershay/1494931 to your computer and use it in GitHub Desktop.
bash golf problem
#!/bin/bash
# Input:
# output this 6
# do not output this 5
# output this 7
#
# Output (and a non-zero exit code):
# output this 6
# output this 7
THRESHOLD=5
cat test_file |
ruby -ne "puts \$_ if \$_.split(' ').last.to_i > \"${THRESHOLD}\".to_i" | \
ruby -e 'out = STDIN.read; puts out; exit(1) if out.length > 0'
@xaviershay
Copy link
Author

Combined above solutions to this:

#!/bin/bash

THRESHOLD=5

! cat test_file | \
  awk "\$NF > $THRESHOLD { print }" | \ # $NF = last field
  egrep ".+"                            # Set exit code if no output,
                                        # negated by preliminary `!`

@telemachus
Copy link

You can remove the cat and apply the awk line directly to the test_file - if we're still golfing.

awk "\$NF > $THRESHOLD { print }"  test_file

@floere
Copy link

floere commented Dec 19, 2011

Beautiful! :D

(Whoops! Accidental +1, sorry!)

@i5513
Copy link

i5513 commented Apr 29, 2016

@telemachus , you dont need print statement, it is the default behaviour

awk -v t=$THRESHOLD '$NF > t' test_file

Untested , but i'm sure it work , and less readable but shorter:

awk '$NF>'$THRESHOLD test_file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment