Escaping quotes in zsh alias
You could use a zsh function instead of an alias. No quoting hoops to jump through.
striplines() {
awk '... awk body "with quotes" ...' "$@"
}
To get an idea of what's going on, run
% alias striplines='print -lr awk " /^$/ {print \"\n\"; } /./ {printf( \" %s \",$0);}"'
% striplines
awk
/^$/ {print "\n"; } /./ {printf( " %s ",zsh);}
Since the $
characters are in double quotes (when they're expanded after the alias is expanded), they are interpreted by the shell. To get the quoting right, it's easier to put the whole alias definition in single quotes. What's inside the single quotes is what will be expanded when the alias is used. Now that the argument of awk
is surrounded in double quotes, it's clear that you need backslashes before \"$
.
alias striplines='print -lr awk " /^\$/ {print \"\n\"; } /./ {printf( \" %s \",\$0);}"'
A useful idiom to single-quote a single-quoted string is that '\''
is pretty much a way to put a literal single quote in a single-quoted string. Technically there's a juxtaposition of a single-quoted string, a backslash-quoted '
, and another single-quoted string. The juxtaposed empty string ''
at the end can be removed.
alias striplines='print -lr awk '\'' /^$/ {print "\n"; } /./ {printf( " %s ",$0);}'\'
After this long explanation, a recommendation: when it's too complicated for an alias, use a function.