user1052610
user1052610

Reputation: 4719

Unix tail and grep equivalent for Windows

We have the following unix command:

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

This:

  1. /usr/bin/tail -n 1 %{path} gets the last line in the file that the path variable refers to

  2. | grep --silent -F "%{message}" pipes the output to another command, grep, which checks if the output of the previous command is equal to the value of message

  3. && rm -f %{path}% if the values are equal, then delete the file refered to by path

The above line is in a configuration file which is allows for calls to be made to the underlying operating system.

I want to replicate the functionalirty on windows. I tried this:

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

This error is thrown:

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

Line 15 is the line in the configuration file which contains the above.

Thanks

Upvotes: 2

Views: 7819

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200453

PowerShell solution:

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

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

If you want to run it from a command line, call it like this:

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

Upvotes: 3

npocmaka
npocmaka

Reputation: 57282

You can use tailhead.bat (pure batch script utility) that can be used to show lasts/fists lines of a file.Instead of Grep you can use findstr or find :

tailhead.bat tailhead -file=%pathToFile% -begin=-3|find  "%message%"

Upvotes: 1

Related Questions