-1

I'm trying to see if there is a string that exists in a particular text file that I have. I already referred to this post but I'm having different issues.

I'm running this as a batch file in powershell with ./test.bat.

if [ "$(< C:/Temp/test.txt)" =~ "test" ]; then echo "true"

This returns "$(C:/Temp/test.txt)" was unexpected at this time.

I also tried

if grep -` "test" "$C:/Temp/test.txt"; then echo "True"

This returns -q was unexpected at this time.

What am I doing wrong?

5
  • 2
    You're using the syntax of POSIX-compatible shells, such as Bash. Batch files have very different syntax. Commented Oct 12, 2023 at 15:24
  • 2
    findstr test c:\temp\test.txt >NUL && echo True is roughly the batch-file equivalent. Commented Oct 12, 2023 at 15:27
  • 1
    Or, less roughly, for the case insensitive substring: @"%SystemRoot%\System32\find.exe" /I "test" 0<"C:\Temp\test.txt" 1>NUL 2>&1 && (Echo True) || Echo False, or for the case insensitive word: @"%SystemRoot%\System32\findstr.exe" /I /M /R "\<test\>" "C:\Temp\test.txt" 1>NUL 2>&1 && (Echo True) || Echo False. Commented Oct 12, 2023 at 16:07
  • 1
    @mklement0 is there an "else" equivalent? What if I want to throw an error or stop the batch file if the condition is not true? Commented Oct 12, 2023 at 16:14
  • 2
    @Sarah, you can then use the or conditional statement which is || as per example.findstr test "c:\temp\test.txt" >NUL && echo True || echo False or in the example where you also then want to exit. findstr test "c:\temp\test.txt" >NUL && echo True || (echo False & exit /b 1) Commented Oct 12, 2023 at 17:04

1 Answer 1

-1

To check if there's a string there in a specific file or not you can use grep command.

grep -i -o "<your_string>" <your_file_name>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.