powershell - Windows 下的 Unix tail 和 grep 等效项

标签 powershell batch-file

我们有以下 unix 命令:

/usr/bin/tail -n 1 %{path} | grep --silent -F "%{message}" && rm -f %{path}%

这个:

  1. /usr/bin/tail -n 1 %{path} 获取 path 变量引用的文件中的最后一行

  2. | grep --silent -F "%{message}" 将输出通过管道传输到另一个命令 grep,该命令检查前一个命令的输出是否等于 的值消息

  3. && rm -f %{path}% 如果值相等,则删除 path 引用的文件

上面的行位于配置文件中,允许调用底层操作系统。

我想在 Windows 上复制该功能。 我试过这个:

command => 'powershell -Command "& {Get-Item $args[0] | ? { (Get-Content $_ -Tail 1).Contains($args[1]) }| Remove-Item -Force}" "'%path%'" "'%message%'"'

抛出此错误:

Error: Expected one of #, {, } at line 15, column 131 (byte 498)

第 15 行是配置文件中包含上述内容的行。

谢谢

最佳答案

PowerShell 解决方案:

$path    = 'C:\path\to\your.txt'
$message = 'message'

Get-Item $path | ? { (Get-Content $_ -Tail 1).Contains($message) } | Remove-Item -Force

如果您想从命令行运行它,请像这样调用它:

powershell -Command "& {Get-Item $args[0] | ? { (Get-Content $_ -Tail 1).Contains($args[1]) } | Remove-Item -Force}" "'C:\path\to\your.txt'" "'message'"

关于powershell - Windows 下的 Unix tail 和 grep 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31136733/

相关文章:

powershell - VSTS将变量传递到Azure PowerShell脚本参数

powershell - 如何在 PowerShell 中连接两个文本文件?

azure - 如何在通过 Azure CLI 检索时设置不记名 token 的生命周期?

windows - “RD”命令在成功或失败时不返回 '0' 或 '1' 作为错误级别

java - JDBC插入多行

delphi - 使用批处理脚本检测文件损坏

sql-server - 如何使用 SMO 脚本生成器生成 sql 脚本

sharepoint - 如何纠正此自动删除Sharepoint备份的PowerShell脚本

powershell - PowerShell 是批处理文件的良好升级吗?

popup - 如何在批处理脚本中创建弹出消息?