LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   multi-line comments in sed (https://www.linuxquestions.org/questions/linux-newbie-8/multi-line-comments-in-sed-4175619818/)

Reprovo 12-18-2017 09:25 AM

multi-line comments in sed
 
Hi. I found the below example regarding pre-processing a multi-line variable in SED by using '/' forward slashes.

Code:

VAR='content with
multiple lines
  some with lead blanks
or even backslash\'

preprocessed_VAR=$(printf '%s\n' "$VAR" |

sed 's/\\/&&/g;s/^[[:blank:]]/\\&/;s/$/\\/')


sed -i -e "/i/a ${preprocessed_VAR%?}" test_append


What I don't understand is why the "%?" is removing all the added forward slashes in the below command:

Code:

  sed -i -e "/i/a ${preprocessed_VAR%?}" test_append
giving the below output in the test_append file:

content with
multiple lines
some with lead blanks
or even backslash\

If I just run:

Code:

${echo ${preprocessed_VAR%?}
i get the following:

content with\ multiple lines\ \ some with lead blanks\ or even backslash\\

It's removing only the last '\' as expected.

What's the difference in the SED command that removes all the added '\' ?

keefaz 12-18-2017 11:34 AM

Because sed interprets escaped characters like echo -e

pan64 12-18-2017 11:56 AM

${preprocessed_VAR%?} is an expression in bash, not related to sed at all, see man bash, look for ${parameter%word}
If you want to check the content of a variable, use ":
Code:

user@host:/tmp$ VAR='content with
> multiple lines
>  some with lead blanks
> or even backslash\'
user@host:/tmp$ echo "$VAR"
content with
multiple lines
  some with lead blanks
or even backslash\
user@host:/tmp$ preprocessed_VAR=$(printf '%s\n' "$VAR" | sed 's/\\/&&/g;s/^[[:blank:]]/\\&/;s/$/\\/')
pan@suni:/tmp/film$ echo "${preprocessed_VAR}"
content with\
multiple lines\
\  some with lead blanks\
or even backslash\\\
user@host:/tmp$ echo "${preprocessed_VAR%?}"
content with\
multiple lines\
\  some with lead blanks\
or even backslash\\
host@user:/tmp$

your sed command will append the content of that variable in every line where at least one i was found.
When you execute the sed the \ inside the sed expression will be evaluated before executing the sed command itself.


All times are GMT -5. The time now is 09:28 AM.