Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 60 lines (50 sloc) 1.59 KB
#!/usr/bin/env bash
# =============================================================================
# Trim front of file
# By Justin Sternberg <me@jtsternberg.com>
# https://github.com/jtsternberg/Dot-Files/blob/master/bin/trim-front
#
# Version 0.1.0
#
# Takes a file path as the first parameter,
# and (optionally) a second parameter to
# specify the number of lines to keep.
#
# If file has more lines than the number to keep,
# this script will trim the front of the file.
#
# Useful for purging old data in a log file.
#
# Usage:
# trim-front debug.log 1000
# =============================================================================
# If no first argument (a file path),
if [ -z "$1" ]
then
# then throw a message
errmsg 'Please specify a file to trim, and optionally, number of lines to keep. (Also, be sure to backup)' 'red'
exit 1
fi
# If the file doesn't exist
if [ ! -f "$1" ]
then
# throw a message
errmsg 'There was an error with the file path provided. Does the file exist?' 'red'
exit 1
fi
file_path=$1
# Default to 500 lines to keep
lines_to_keep=${2:-500}
# Get number of lines in file (w/o filename)
lines_of_code=$(wc -l < "$file_path")
# Calculate lines that will be trimmed from front
to_trim=$((lines_of_code-lines_to_keep))
# If the lines to trim is greater than 0
if [ "$to_trim" -gt 0 ]
then
# the magic command.. edits file in-place, and trim X lines from front
sed -i -e "1,${to_trim}d" "$file_path"
errmsg "$lines_of_code total lines, $to_trim lines trimmed, and $lines_to_keep lines left."
else
errmsg "$lines_of_code total lines, not enough to trim." 'red'
fi