François Patte wrote:
> I want to insert some latex commands (\phantomsection and \ label) after
Probably you mean without the space after the second backslash.
> the string "begin" in a file the name of which is given by a variable:
> $file.
>
> Here is what I have done:
>
> sed -i "/begin/ s/$/ \\\\\\phantomsection \\\\\\label{$file}/" "$file"
>
> but, this works only for \phantomsection and, for the command \label,
> it returns \abel!
If you investigate the expansion, you can see why:
| $ printf '%s\n' "/begin/ s/$/ \\\\\\phantomsection \\\\\\label/"
| /begin/ s/$/ \\\phantomsection \\\label/
The second line is what sed(1) will see, where
“\\” is the sed(1) escape sequence for one backslash character (“\”);
“\p” is an unsupported sed(1) escape sequence, so it is parsed as “p”;
“\l” is a GNU sed(1) extension:
| File:
sed.info, Node: The "s" Command, […] Up: sed Programs
|
| […] Finally, as a GNU 'sed' extension, you can include a special sequence
| made of a backslash and one of the letters 'L', 'l', 'U', 'u', or 'E'.
| The meaning is as follows:
|
| '\L'
| Turn the replacement to lowercase until a '\U' or '\E' is found,
|
| '\l'
| Turn the next character to lowercase,
| […]
The next character in your case is “{”, so the “\l” is discarded and nothing
else changes.
> How can I retrieve \label?
By using only 4 backslashes if you use a double-quoted string.
| $ echo 'begin' | sed "/begin/ s/$/ \\\\phantomsection \\\\label/"
| begin \phantomsection \label
Because that is what sed(1) will see:
| $ printf '%s\n' "/begin/ s/$/ \\\\phantomsection \\\\label/"
| /begin/ s/$/ \\phantomsection \\label/
> Moreover is it necessary to have six backslash to retrieve only one?
No. (How did you get that idea in the first place?)
| $ echo 'begin' | sed '/begin/ s/$/ \\phantomsection \\label/'
| begin \phantomsection \label
> If I put single quotes, I need only two backslash, but the variable $file
> is not expanded...
You can switch between expansion and non-expansion by concatenation. I have
marked the string literals below (use a fixed-width font):
sed -i '/begin/ s/$/ \\phantomsection \\label{'"$file"'}/' "$file"
^ ^^ ^^ ^ ^ ^
'--------------------------------------''-----''--' '-----'
However, be aware that you need to escape any sed-special character
sequences in what the first "$file" expands to.
--
PointedEars
Twitter: @PointedEars2
Please do not cc me. /Bitte keine Kopien per E-Mail.