fork download
  1. #!/bin/bash
  2.  
  3. # The need is to only replace $pattern inside $whole_text, and return the rest
  4. # of the input untouched. But currently is only returning the matched line.
  5.  
  6. # I'm not sure if it's needed, but as @EdMorton recommends, it may be good idea
  7. # to import the variables in a safer way, as explained here:
  8. # http://c...content-available-to-author-only...n.com/shell/cus-faq-2.html#Q24
  9. #
  10. # Form "d" seems to be the best for compatibility and features:
  11. #
  12. # awk 'BEGIN{avar=ARGV[1];ARGV[1]=""}$0 == avar' "$svar" file
  13.  
  14. # The following variables really can contain ANY printable character.
  15. # But in order to simplify, here they don't support single quotes.
  16. pattern='<!-- %cmd: for F in $(find ../[0-9]* -maxdepth 0 -type d | sed "s/^\.\.\///"); do echo "<li><a href=\"$F\">$F</a></li>"; done -->'
  17. container='
  18. <h2>Title</h2>
  19. <ul>
  20. <!-- %cmd: for F in $(find ../[0-9]* -maxdepth 0 -type d | sed "s/^\.\.\///"); do echo "<li><a href=\"$F\">$F</a></li>"; done -->
  21. </ul>
  22. '
  23. container2="line 1\nline 2\n$pattern\nline3\nline4"
  24.  
  25. echo "-------- A: anuhava proposal d22"
  26. echo "-------- problem: doesn't print non-matched lines"
  27.  
  28. awk -v repl="newtext" 'FNR==NR {
  29. a = a $0; next
  30. }
  31. n = index($0, a) {
  32. print substr($0, 1, n-1) repl substr($0, n+length(a))
  33. }' <(printf "%s\n" "$pattern") <(echo "$container")
  34.  
  35.  
  36.  
  37. echo "-------- B: anubhava proposal d29 15:30"
  38. echo "-------- It seems to work, need to check receiving text through variable (see C)"
  39.  
  40. awk -v repl="newtext" 'FNR==NR {
  41. a = a $0; next
  42. } n = index($0, a) {
  43. $0 = substr($0, 1, n-1) repl substr($0, n+length(a))
  44. } 1' <(printf "%s\n" "$pattern") <(printf 'line 1\nline 2\nbefore %s after\nline 3\nline 4\n' "$pattern")
  45.  
  46.  
  47. echo "-------- C: modified last proposal to receive container text through variable"
  48. echo "-------- IT WORKS!"
  49.  
  50. awk -v repl="newtext" 'FNR==NR {
  51. a = a $0; next
  52. } n = index($0, a) {
  53. $0 = substr($0, 1, n-1) repl substr($0, n+length(a))
  54. } 1' <(printf "%s\n" "$pattern") <(printf '%s' "$container")
  55.  
Success #stdin #stdout 0s 5896KB
stdin
Standard input is empty
stdout
-------- A: anuhava proposal d22
-------- problem: doesn't print non-matched lines
        newtext
-------- B: anubhava proposal d29 15:30
-------- It seems to work, need to check receiving text through variable (see C)
line 1
line 2
before newtext after
line 3
line 4
-------- C: modified last proposal to receive container text through variable
-------- IT WORKS!

    <h2>Title</h2>
    <ul>
        newtext
    </ul>