Re: Including ' in a sed command
On 08/08/2025 14:24, Bob McGowan wrote:
On 8/7/25 07:17 PM, Tim Woodall wrote:
sed 's/["'"'"']//'
[...]
Have you considered using '-f scriptfile'?
Your regex goes in the file and completely eliminates issues of
collisions with shell metacharacters.
I am realizing that Tim's case may be handled by "tr -d", but "sed -f"
gave me another idea. It is inconvenient to have small scripts in
separated files. However if some file is processed (not standard input)
then with some care the script may be inlined. (I am just using sed
script from another message, I have not tested if it really can make
something useful. Let's concentrate on quotes, apostrophes, and escaping.)
sed -f - file.yaml <<'EOF'
s/.*\$ref["']\{0,1\}: *["']\([^"']*\)["'].*/\1/
EOF
It is not as convenient as raw string literals in C++
R"SED(s/.*\$ref["']\{0,1\}: *["']\([^"']*\)["'].*/\1/)SED"
or in Python
r"""s/.*\$ref["']\{0,1\}: *["']\([^"']*\)["'].*/\1/"""
but still might be helpful.
A variable may be used if sed reads data from standard input, but there
are more pitfalls with stripping spaces
# IFS=
read -r script_read <<-'SED_SCRIPT'
s/.*\$ref["']\{0,1\}: *["']\([^"']*\)["'].*/\1/
SED_SCRIPT
... | sed -e "$script_read" ...
There is another variant with its own downsides, and basing on [1], I
expect that Greg W will be strongly against it (subshell, stripping
trailing spaces):
script_func()
{
cat <<-'SED_SCRIPT'
s/.*\$ref["']\{0,1\}: *["']\([^"']*\)["'].*/\1/
SED_SCRIPT
}
... | sed -e "$(script_func)" ...
[1] Greg Wooledge. Re: Is there a POSIX compliant way of turning a
"HH:MM:SS" formatted string to seconds? ...
Sat, 19 Jul 2025 22:45:31 -0400.
<https://lists.debian.org/msgid-search/20250720024531.GV28766@wooledge.org>
Reply to: