gpt4 book ai didi

r - 在R中运行Powershell的转义字符

转载 作者:行者123 更新时间:2023-12-02 23:35:06 25 4
gpt4 key购买 nike

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

How do I grep a date pattern from a list of csv files in powershell?

问题是在R的system命令中实现此功能时:

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中'...'字符串文字中的转义字符。

因此,为了传递文字\ char。通过,您必须\-转义它,即将它加倍;在您的情况下,这表示将\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,而该序列恰好不受支持。

关于r - 在R中运行Powershell的转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57582168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com