代码之家  ›  专栏  ›  技术社区  ›  Conner M.

R-如何使用system()或system2()执行PowerShell cmds

  •  1
  • Conner M.  · 技术社区  · 6 年前

    我在R(在Windows操作系统上)中工作,试图计算文本文件中的字数,而不将该文件加载到内存中。其思想是获取文件大小、行数、字数等的一些统计信息 find How do I do a "word count" command in Windows Command Prompt

    lineCount <- system(paste0('find /c /v "" ', path), intern = T)
    

    我尝试使用的字数计数命令是PowerShell命令: Measure-Object . 我可以让下面的代码运行而不抛出错误,但它返回了不正确的计数。

    print(system2("Measure-Object", args = c('count_words.txt', '-Word')))
    [1] 127
    

    count_words.txt 已经有数百万字了。我还在一个字少得多的.txt文件上测试了它。

    "There are seven words in this file."
    

    但计数再次返回为127。

    print(system2("Measure-Object", args = c('seven_words.txt', '-Word')))
    [1] 127
    

    system2() 测量对象 ? 为什么不管实际字数多少,它都返回相同的值?

    1 回复  |  直到 6 年前
        1
  •  2
  •   duckmayr    6 年前

    问题——概述

    所以,这里有两个问题:

    1. system2() 使用powershell

    解决方案

    command <- "Get-Content C:/Users/User/Documents/test1.txt | Measure-Object -Word"
    system2("powershell", args = command)
    

    替换位置 C:/Users/User/Documents/test2.txt

    command <- "Get-Content C:/Users/User/Documents/test1.txt | Measure-Object -Word"
    system2("powershell", args = command)
    
    Lines                             Words Characters          Property           
    -----                             ----- ----------          --------           
                                          7                                        
    
    
    command <- "Get-Content C:/Users/User/Documents/test2.txt | Measure-Object -Word"
    system2("powershell", args = command)
    
    Lines                             Words Characters          Property           
    -----                             ----- ----------          --------           
                                          8                                        
    

    更多解释

    help("system2") :

    system2调用command指定的OS命令。

    一个主要问题是 Measure-Object 不是系统命令,而是PowerShell命令。PowerShell的系统命令为 powershell ,这是您需要调用的。

    此外,您还没有完全正确的PowerShell语法。如果你看看 the docs ,您将看到真正需要的PowerShell命令是

    Get-Content C:/Users/User/Documents/count_words.txt | Measure-Object -Word