Skip to content

Instantly share code, notes, and snippets.

@mzpqnxow
Last active July 22, 2021 17:47
Show Gist options
  • Save mzpqnxow/d49c45af025de5807335572d5a8f77fc to your computer and use it in GitHub Desktop.
Save mzpqnxow/d49c45af025de5807335572d5a8f77fc to your computer and use it in GitHub Desktop.
In place grep - why would anyone want to do such a thing!?
#!/bin/bash
#
# WARNING: YOU WILL LOSE THE FILE IF YOU SCREW UP BE CAREFUL
# If UNSAFE is set to YES, no backup will occur; you better not screw up!
# grep args or pattern because your file will be gone :>
#
# - AG
set -Eu
declare -r UNSAFE=YES
declare TMPDIR="/dev/shm"
if [ $# -lt 2 ]; then
echo "--- grepi: inline replacing grep wrapper"
echo "Usage:"
echo ' grepi [flags] <pattern> <filename>'
exit 1
fi
# Override environment TMPDIR by default
if [ ! -d "$TMPDIR" ]; then
# Pick out any tmpfs mounts that do not have an explicit owner or perm mode
# By default, the mode for tmpfs is 1777, same as traditional /tmp mounts
# Typical systems have /run/lock and /dev/shm, both are suitable
TMPDIR="$(mount | grep -P 'tmpfs(?!.*(mode|[^s]uid=))' | awk '{print $3}' | head -1)"
if [ "$TMPDIR" == "" ]; then
TMPDIR="/tmp"
fi
fi
# Last arg is the filename
declare -r file="${*: -1}"
# All the rest are grep parameters
declare -a args="${@:1:$#-1}"
if [ "${UNSAFE:-}" != "YES" ]; then
declare -r basefile="$(basename "$file")"
declare -r backup="$(realpath "$TMPDIR/$file")"
echo "Backing file original=$file backup=$backup'"
cp "$file" "$TMPDIR/"
echo
echo "To restore:"
echo " mv $backup $file"
echo
fi
echo "Invoking grep in-place on file=$file"
echo " $args"
ls -l "$file"
(rm $file; grep ${args[@]} > "$file") < "$file"
ls -l "$file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment