Skip to content

Instantly share code, notes, and snippets.

@otherjoel
Created October 7, 2016 20:36
Show Gist options
  • Save otherjoel/1be35c9dec01b147e019641a2437d082 to your computer and use it in GitHub Desktop.
Save otherjoel/1be35c9dec01b147e019641a2437d082 to your computer and use it in GitHub Desktop.
Script to find a line in a text file (based on an environment variable) and increment a value within that line
#!/bin/bash
# Script to find a line in a text file (based on an environment variable) and increment a value within that line
# In this example, the text file has several lines of the form "<ip address>,<number>"
# Add a line for this IP address if it doesn't exist
grep -q -F $REMOTE_ADDR hits.txt || echo "$REMOTE_ADDR,0" >> hits.txt
# Increase the count for this IP address
sed -r -i 's/'"$REMOTE_ADDR"',([0-9]+)/echo "$REMOTE_ADDR,$((\1+1))"/ge' /d2a/4weeks/shipreporthits.txt
# In bash you can jamme single-quoted and double-quoted strings up against each other:
# 'simple stuff'"this one has a $VAR"'.etc...'
# This is way simpler than trying to figure out nested escaping, etc.
# -i option edits file in-place
# The 'e' option in '/ge' allows you to use an external command for the replacement, and pass it the matches.
# See http://stackoverflow.com/questions/14348432/how-to-find-replace-and-increment-a-matched-number-with-sed-awk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment