Skip to content

Instantly share code, notes, and snippets.

@Hubro
Created January 23, 2015 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hubro/d0f05c010edad6465326 to your computer and use it in GitHub Desktop.
Save Hubro/d0f05c010edad6465326 to your computer and use it in GitHub Desktop.
Command for appending/prepending text to lines
#!/bin/bash
# Append/prepend text to line
function usage
{
echo -e "Usage: $(basename "$0") [a|p] TEXT"
echo
echo -n "apline reads from standard input and appends/prepends TEXT to "
echo "each line."
exit 1
}
[[ $# > 2 || $# -eq 0 ]] && usage
if [[ $# -eq 1 ]]
then
ACTION="p"
TEXT="$1"
else
ACTION="$1"
TEXT="$2"
fi
[[ "$ACTION" != "a" && "$ACTION" != "p" ]] && usage
INSERT=1
while IFS= read -d "" -s -N 1 CHAR
do
[[ -n "$INSERT" && "$ACTION" == "p" ]] && printf "%s" "$TEXT"
[[ "$CHAR" == $'\n' && "$ACTION" == "a" ]] && printf "%s" "$TEXT"
printf "$CHAR"
unset INSERT
[[ "$CHAR" == $'\n' ]] && INSERT=1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment