0

I want to change this:

...
 %%%23begin
 aaaaaaa \\
 bbbbbbb \\
 ccccccc \\
 %%%23end
 ...

to this

 ...
 %%%23begin
 xxxxxxxx \\
 yyyyyyyy \\
 zzzzzzzzz \\
 tttttttt \\
 %%%23end
 ...

the number of lines might change after editing.

using this function :

function editEntry(){
  local entryIndex="$1"
  local pattern='^%%%'$entryIndex'begin'
  d1=$(grep -n "$pattern" "$theBook" | cut -d: -f 1)
  d1=$((d1+1))
  local pattern='^%%%'$entryIndex'end'
  d2=$(grep -n "$pattern" "$theBook" | cut -d: -f 1)
  d2=$((d2-1))
  local text1=$(sed  -n "$d1,$d2"p "$theBook")
  echo "$text1" >| "$tmpfile"
  gedit "$tmpfile" && local text2=$(cat "$tmpfile" ) 
  sed -i "s@$text1@$text2@" "$theBook"
}

apparently sed does not change entire paragraphs , it only operates on lines

4
  • What change do you want to make? It looks like you want to operate on the lines between 23begin and 23end, is that right? Please edit your question and show us your desired output so we can understand what you need.
    – terdon
    Dec 3, 2018 at 19:10
  • yes that's what I want and sed could not do the job
    – Neo Mosaid
    Dec 3, 2018 at 19:15
  • In the expected answer do you still want to be able to manually edit $text1 into $text2? Which would mean that you are just looking for an easier way to extract the text between 23begin and 23end, right?
    – nohillside
    Dec 3, 2018 at 19:20
  • actually I can extract it, I want an easy way to replace it after I have edited it
    – Neo Mosaid
    Dec 3, 2018 at 19:23

1 Answer 1

3

Scripting text edits is what ed is for:

ed file <<'SCRIPT'
/%%%23begin/+1,/%%%23end/-1d
/%%%23begin/a
 xxxxxxxx \\
 yyyyyyyy \\
 zzzzzzzzz \\
 tttttttt \\
.
wq
SCRIPT

First, delete the contents between (but not including) the markers, then append the desired text after the start marker. "Dot" ends input. Save and quit.

3
  • the function above is a part of a lager bash script that makes the file, and it contains arabic characters that's way I used gedit.
    – Neo Mosaid
    Dec 3, 2018 at 19:29
  • here is what I did based on your answer ` printf " /$pattern1/+1,/$pattern2/-1d \n /$pattern1/a $text2 \n . \n wq \n SCRIPT " | ed -s "$theBook" ` but it didn't work
    – Neo Mosaid
    Dec 3, 2018 at 19:55
  • If you want to use printf: printf '%s\n' "/$pattern1/+1,/$pattern2/-1d" "/$pattern1/a" "$text2" . wq | ed -s "$theBook" -- the "SCRIPT" is the heredoc terminator, not an ed command. Dec 3, 2018 at 20:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .