_sed 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/bin/bash
  2. # https://github.com/YunoHost/yunohost/pull/394
  3. # Substitute/replace a string (or expression) by another in a file
  4. #
  5. # usage: ynh_replace_string match_string replace_string target_file
  6. # | arg: match_string - String to be searched and replaced in the file
  7. # | arg: replace_string - String that will replace matches
  8. # | arg: target_file - File in which the string will be replaced.
  9. #
  10. # As this helper is based on sed command, regular expressions and
  11. # references to sub-expressions can be used
  12. # (see sed manual page for more information)
  13. ynh_replace_string () {
  14. local delimit=@
  15. local match_string=$1
  16. local replace_string=$2
  17. local workfile=$3
  18. # Escape the delimiter if it's in the string.
  19. match_string=${match_string//${delimit}/"\\${delimit}"}
  20. replace_string=${replace_string//${delimit}/"\\${delimit}"}
  21. sudo sed --in-place "s${delimit}${match_string}${delimit}${replace_string}${delimit}g" "$workfile"
  22. }
  23. # Substitute/replace a password by another in a file
  24. #
  25. # usage: ynh_replace_password_string match_string replace_string target_file
  26. # | arg: match_string - String to be searched and replaced in the file
  27. # | arg: replace_string - String that will replace matches
  28. # | arg: target_file - File in which the string will be replaced.
  29. #
  30. # This helper will use ynh_replace_string, but as you can use special
  31. # characters, you can't use some regular expressions and sub-expressions.
  32. ynh_replace_password_string () {
  33. local match_string=$1
  34. local replace_string=$2
  35. local workfile=$3
  36. # Escape any backslash to preserve them as simple backslash.
  37. match_string=${match_string//\\/"\\\\"}
  38. replace_string=${replace_string//\\/"\\\\"}
  39. # Escape the & character, who has a special function in sed.
  40. match_string=${match_string//&/"\&"}
  41. replace_string=${replace_string//&/"\&"}
  42. ynh_replace_string "$match_string" "$replace_string" "$workfile"
  43. }