On linux I can rappresent the / char in a different way:
${HOME:0:1}
So, for example, cat ${HOME:0:1}etc${HOME:0:1}passwd
would be treated like cat /etc/passwd
Is there any way I can do the same thing on windows via powershell and cmd.exe for the backslash?
CodePudding user response:
PowerShell has no equivalent to the parameter expansions available in POSIX-compatible shells such as Bash, of which your substring extraction (${HOME:0:1}
to get the substring of length 1
at character position 0
, i.e the first char. of the value of variable $HOME
) is an example (link is to the Bash manual).
However, PowerShell makes it easy:
to embed the results of arbitrary expressions and even whole statements inside expandable (double-quoted) string (
"..."
), using$(...)
, the subexpression operator.to pass the results of any expression or command (pipeline) as an argument to a command, by enclosing it in
(...)
, the grouping operator.
The following command variations are equivalent, and dynamically use the platform-appropriate path (directory) separator, i.e. /
on Unix-like platforms, and \
on Windows:
# -> '/etc/passwd' on Unix
# -> '\etc\passwd' on Windows
Write-Output "$([System.IO.Path]::DirectorySeparatorChar)etc$([System.IO.Path]::DirectorySeparatorChar)passwd"
# Ditto.
Write-Output ('{0}etc{0}passwd' -f [System.IO.Path]::DirectorySeparatorChar)
See also:
-f
, the string format operator