-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrim-front
executable file
·59 lines (50 loc) · 1.59 KB
/
trim-front
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/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