首页 > 解决方案 > 在 R 中运行 powershell 时出现转义字符

问题描述

尝试在 R 中运行 powershell 命令专门过滤日期目录,这是基于我之前提出的一个问题:

如何从powershell中的csv文件列表中grep日期模式?

问题是在 R 的系统命令中实现这个时:

files = system('powershell -command "Get-ChildItem \'D:/my_directory\' | Where-Object {($_.Name -match \'[\d]{4}-[\d]{2}-[\d]{2}\') -and ([datetime][regex]::Match($_.Name, \'[\d]{4}-[\d]{2}-[\d]{2}\').Value -ge (Get-Date 2017/01/01)) -and ([datetime][regex]::Match($_.Name, \'[\d]{4}-[\d]{2}-[\d]{2}\').Value -le (Get-Date 2017/03/01))})"', intern = T)

原来的:

Get-ChildItem "D:/shl" | Where-Object {($_.Name -match "[\d]{4}-[\d]{2}-[\d]{2}") -and ([datetime][regex]::Match($_.Name, "[\d]{4}-[\d]{2}-[\d]{2}").Value -ge (Get-Date 2017/01/01)) -and ([datetime][regex]::Match($_.Name, "[\d]{4}-[\d]{2}-[\d]{2}").Value -le (Get-Date 2017/03/01))}

似乎我没有正确逃脱?

Error: '\d' is an unrecognized escape in character string starting "'powershell -command "Get-ChildItem \'D:/my_directory\' | Where-Object {($_.Name -match \'[\d"

尝试了建议的解决方案:

system('powershell -command "Get-ChildItem \'my_directory\' | Where-Object {($_.Name -match \'[\\d]{4}-[\\d]{2}-[\\d]{2}\') -and ([datetime][regex]::Match($_.Name, \'[\\d]{4}-[\\d]{2}-[\\d]{2}\').Value -ge (Get-Date 2017/01/01)) -and ([datetime][regex]::Match($_.Name, \'[\\d]{4}-[\\d]{2}-[\\d]{2}\').Value -le (Get-Date 2017/03/01))})"', intern = T)  

收到以下警告:

[1] "At line:1 char:283"                                                                   
[2] "+ ... _.Name, '[\\d]{4}-[\\d]{2}-[\\d]{2}').Value -le (Get-Date 2017/03/01))})"       
[3] "+                                                                         ~"          
[4] "Unexpected token ')' in expression or statement."                                     
[5] "    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException"
[6] "    + FullyQualifiedErrorId : UnexpectedToken"                                        
[7] " "                                                                                    
attr(,"status")
[1] 1

更新:

固定的:

system('powershell -command "Get-ChildItem \'D:/my_directory\' | Where-Object {($_.Name -match \'[\\d]{4}-[\\d]{2}-[\\d]{2}\') -and ([datetime][regex]::Match($_.Name, \'[\\d]{4}-[\\d]{2}-[\\d]{2}\').Value -ge (Get-Date 2017/01/01)) -and ([datetime][regex]::Match($_.Name, \'[\\d]{4}-[\\d]{2}-[\\d]{2}\').Value -le (Get-Date 2017/03/01))}"')

标签: rpowershell

解决方案


它看起来\被用作'...'R 中字符串文字中的转义字符。

因此,为了传递一个文字 \字符。通过,你将不得不\-escape 它,即加倍它;在您的情况下,这意味着\d将要传递给正则表达式引擎的实例表示为\\d

files = system('powershell -command "Get-ChildItem \'D:/my_directory\' | Where-Object {($_.Name -match \'[\\d]{4}-[\\d]{2}-[\\d]{2}\') -and ([datetime][regex]::Match($_.Name, \'[\\d]{4}-[\\d]{2}-[\\d]{2}\').Value -ge (Get-Date 2017/01/01)) -and ([datetime][regex]::Match($_.Name, \'[\\d]{4}-[\\d]{2}-[\\d]{2}\').Value -le (Get-Date 2017/03/01))})"')

错误消息告诉您的是R(而不是 PowerShell)正在尝试解释转义序列\d,这恰好不是受支持的。


推荐阅读