Search for text and strings in files and subdirectories with result in variables
Usually when searching for strings in files, we use windows explorer or windows search, on Linux Gnome uses nautilus or nemo, on macOS we use the finder.
Command-Line commands help with automated processing by scripts and batch processes. This post shows how to search for strings in Windows Command Prompt and in the Linux shell.
Search in the command prompt
The Windows Command Prompt (cmd) a good use provide the findstr command, as the following example shows.
findstr /s /i "dolor" *.* doc.txt:Lorem ipsum dolor sit amet
If you want to assign the result of a variable for further processing in scripts, this can be made possible in a FOR loop, the following lines are stored and executed in a CMD file.
@echo off for /f "delims=" %%A in ('dir ^| findstr /s /i "dolor" *.*') do set "var=%%A" echo %var%
With echo the entire line is output with the searched word dolor, if you want to narrow the output only to the characters of a word, this can be achieved with variable parameters.
doc.txt:Lorem ipsum dolor sit amet 1234567890123456789012345678901234
From the sign 20 our word is dolor, it is 5 characters long.
The CLI input findstr dolor now brings dolor to the output found in the doc.txt file.
@echo off for /f "delims=" %%A in ('dir ^| findstr /s /i %1 *.*') do set "var=%%A" echo %var:~20,5%
The var variable is assigned the output of findstr.
Searching in the Linux Shell
$ grep -r "dolor" * Dokumente/doc.txt:Lorem ipsum dolor sit amet
In the Linux bash Console does grep and find are used.
$ find . -type f -print0 | xargs -0 grep "dolor" ./Dokumente/doc.txt:Lorem ipsum dolor sit amet
The text search with grep is as follows, the result is assigned to the variable var, and output with echo.
$ var=`grep -r "dolor" *` $ echo $var Dokumente/doc.txt:Lorem ipsum dolor sit amet
When searching with grep, you do not want to output the entire line, but only the third word.
$ var=`grep -r "dolor" * | awk '{ print $3 }'` $ echo $var dolor
There are many other possibilities especially in the Linux bash, the command find is very extensive and offers with xargs also regular expressions and other commands for handing over, with find –help you get all possible applications. The only point here is to show an introduction to the application and procedure.