subst 928 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/bash
  2. # Substitute a string in many files. By Serge van den Boom, 20020826
  3. if [ $# -eq 0 ]; then
  4. {
  5. echo "subst: substitute a string in a lot of files."
  6. echo "By Serge van den Boom, 20020826"
  7. echo "Usage: subst <pattern> <file> [...]"
  8. echo -n "'pattern' should be a pattern in the form used by sed, "
  9. echo " like 's/old/new/g'."
  10. } 1>&2
  11. exit 1
  12. fi
  13. PAT="$1"
  14. SEP="${PAT:1:1}"
  15. GREPPAT="${PAT:2}"
  16. eval GREPPAT='${GREPPAT%%'$SEP'*}'
  17. shift
  18. while [ "$#" -gt "0" ]; do
  19. FILE="$1"
  20. echo -n "$FILE: "
  21. grep -q "$GREPPAT" < "$FILE"
  22. EXITVAL=$?
  23. case $EXITVAL in
  24. 0) # Match found
  25. ;;
  26. 1) # No match found
  27. echo "Nothing to do."
  28. shift
  29. continue
  30. ;;
  31. *)
  32. echo "ERROR"
  33. echo "Error: grep returned exit value ${EXITVAL}. Aborted." 1>&2
  34. exit 1
  35. esac
  36. TEMPFILE="${FILE}.patchtree.$$.tmp"
  37. mv -- "$FILE" "$TEMPFILE"
  38. sed -e "$PAT" < "$TEMPFILE" > "$FILE"
  39. rm -- "$TEMPFILE"
  40. echo "Done."
  41. shift
  42. done