r - 在 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))}"')
解决方案
它看起来\
被用作'...'
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
,这恰好不是受支持的。
推荐阅读
- rust - 如何将 Trait 作为应用程序数据传递给 Actix Web?
- laravel - 为什么 Laravel jetstrem 注销 419 问题?
- html - 图像在移动设备上的卡片上出现和消失
- python - 提取的边界图像非常小
- python - 如何在numpy中将一维数组视为(1乘n)二维数组?
- javascript - Leaflet js - 访问 GeoJSON REST Api 的内存泄漏
- reactjs - 将 React 元素添加到静态网站不起作用
- python - PyTorch - 形状不匹配
- javascript - 如何将 Blob URL 转换为文件(图像文件)
- python - 如何从python中的字符串设置变量?