- Finding a File Containing a Particular Text String In Linux Server
- grep command syntax for finding a file containing a particular text string
- How to search and find all files for a given text string
- Task: Search all subdirectories recursively
- Task: Only display filenames
- Task: Suppress file names
- Task: Display only words
- Task: Search for two or more words
- Task: Hide warning spam
- Task: Display matched text in color
- Task: Ignore case
- How do I find all files containing specific text on Linux?
- Finding text strings within files using grep
- Find and replace text within a file using commands
- 7 Answers 7
- Python
- Finding a text string inside a file on a Linux server
- Searching string in file linux
- Find string in file
- Find string in file ignoring cases
- Find string in current directory
- Find string recursively
- Find files that do not contain a string
- Find string recursively in only some specific files
- Find string recursively in all files except the ones that contain certain extensions
- Find string recursively all files including some extensions and excluding others
- Find string recursively in only some specific files and show their filename
- Find files and find a string in them using find
- How to use sed to find and replace text in files in Linux / Unix shell
- Find and replace text within a file using sed command
- Syntax: sed find and replace text
- Examples that use sed to find and replace
- sed command problems
- How to use sed to match word and perform find and replace
- Recap and conclusion – Using sed to find and replace text in given files
Finding a File Containing a Particular Text String In Linux Server
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | grep |
Est. reading time | Less than 2 minutes |
You need to use the grep command. The grep command or egrep command searches the given input FILEs for lines containing a match or a text string.
grep command syntax for finding a file containing a particular text string
The syntax is:
grep » text string to search » directory-path
grep [option] » text string to search » directory-path
grep -r » text string to search «directory-path
grep -r -H » text string to search » directory-path
egrep -R » word-1|word-2 » /path/to/directory
egrep -w -R » word-1|word-2 » directory-path
Let us see some common example on how to use grep to search for strings in files.
How to search and find all files for a given text string
In this example, search for a string called ‘redeem reward’ in all text (*.txt) files located in /home/tom/ directory, use:
$ grep «redeem reward» /home/tom/*.txt
OR
$ grep «redeem reward»
Task: Search all subdirectories recursively
You can search for a text string all files under each directory, recursively with -r option:
$ grep -r «redeem reward» /home/tom/
OR
$ grep -R «redeem reward» /home/tom/
Look for all files containing cacheRoot text on Linux:
grep -R cacheRoot /home/vivek/
Trying to find all files containing specific text on my Linux desktop
Task: Only display filenames
By default, the grep command prints the matching lines. You can pass -H option to print the filename for each match:
$ grep -H -r «redeem reward» /home/tom
Sample outputs:
To just display the filename use the cut command as follows:
$ grep -H -R vivek /etc/* | cut -d: -f1
Sample outputs:
Task: Suppress file names
The grep command shows output on a separate line, and it is preceded by the name of the file in which it was found in the case of multiple files. You can pass the -h option to suppress inclusion of the file names in the output:
$ grep -h -R ‘main()’
Task: Display only words
You can select only those lines containing matches that form whole words using the -w option. In this example, search for word ‘getMyData()’ only in
/projects/ dirctory:
$ grep -w -R ‘getMyData()’
Task: Search for two or more words
Use the egrep command as follows:
$ egrep -w -R ‘word1|word2’
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Task: Hide warning spam
grep command generate error message as follows due to permission and other issues:
No such file or directory
No such device or address
Permission denied
To hide all errors or warning message spam generated by the grep command, append 2>/dev/null to grep command. This will send and hide unwanted output to /dev/null device:
$ grep -w -R ‘getMyData()’
Task: Display matched text in color
Pass the —color option to the grep command display matched text/words in color on the terminal:
Fig.01: grep command in action with colors and hiding the warnings on screen
Task: Ignore case
Our final example ignore case distinctions in both the search PATTERN and the input files:
grep -i -R ‘word’ /path/to/dir
grep -i -r ‘income tax’
How do I find all files containing specific text on Linux?
The syntax is:
egrep ‘pattern’ -rnw /path/to/dir/
egrep ‘word1|word2’ -rnw /home/vivek/backups/
Finding text strings within files using grep
In this example search for lines starting with any lowercase or uppercase letter:
grep «^[a-zA-Z]» -rns
- -r – Recursive search
- -R – Read all files under each directory, recursively. Follow all symbolic links, unlike -r grep option
- -n – Display line number of each matched line
- -s – Suppress error messages about nonexistent or unreadable files
- -w – Only work on words i.e. search only those lines containing matches that form whole words
- -l – Show the name of each input file when match found
- -i – Ignore case while searching
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Find and replace text within a file using commands
How can I find and replace specific words in a text file using command line?
7 Answers 7
- sed = Stream EDitor
- -i = in-place (i.e. save back to the original file)
The command string:
- s = the substitute command
- original = a regular expression describing the word to replace (or just the word itself)
- new = the text to replace it with
- g = global (i.e. replace all and not just the first occurrence)
file.txt = the file name
There’s multitude of ways to achieve it. Depending on the complexity of what one tries to achieve with string replacement, and depending on tools with which user is familiar, some methods may be preferred more than others.
In this answer I am using simple input.txt file, which you can use to test all examples provided here. The file contents:
Bash isn’t really meant for text processing, but simple substitutions can be done via parameter expansion , in particular here we can use simple structure $
This small script doesn’t do in-place replacement, meaning that you would have to save new text to new file, and get rid of the old file, or mv new.txt old.txt
Side note: if you’re curious about why while IFS= read -r ; do . done is used, it’s basically shell’s way of reading file line by line. See this for reference.
AWK, being a text processing utility, is quite appropriate for such task. It can do simple replacements and much more advanced ones based on regular expressions. It provides two functions: sub() and gsub() . The first one only replaces only the first occurrence, while the second — replaces occurrences in whole string. For instance, if we have string one potato two potato , this would be the result:
AWK can take an input file as argument, so doing same things with input.txt , would be easy:
Depending on the version of AWK you have, it may or may not have in-place editing, hence the usual practice is save and replace new text. For instance something like this:
Sed is a line editor. It also uses regular expressions, but for simple substitutions it’s sufficient to do:
What’s good about this tool is that it has in-place editing, which you can enable with -i flag.
Perl is another tool which is often used for text processing, but it’s a general purpose language, and is used in networking, system administration, desktop apps, and many other places. It borrowed a lot of concepts/features from other languages such as C,sed,awk, and others. Simple substitution can be done as so:
Like sed, perl also has the -i flag.
Python
This language is very versatile and is also used in a wide variety of applications. It has a lot of functions for working with strings, among which is replace() , so if you have variable like var=»Hello World» , you could do var.replace(«Hello»,»Good Morning»)
Simple way to read file and replace string in it would be as so:
With Python, however, you also need to output to new file , which you can also do from within the script itself. For instance, here’s a simple one:
Источник
Finding a text string inside a file on a Linux server
By Adam
Post date
It never fails that I find myself hunting for a way to search for a particular text string in files. Usually I know the file, but often times I also find that I am completely unsure what file contains the string. Or while I am writting some code I need to find how many files use a certain function.
I know that using grep is the best way to search on a Linux server, so I start there. Here is the command syntax:
grep «text string to search for» /path/to/search
Examples
To search for a string called “myFunction” in all text files located in /var/www/html/*.php use:
grep «myFunction» /var/www/html/*.php
To search recursively in all sub-directories you would alter the command by adding the -r option:
grep -r «myFunction» /var/www/html
Now you have probably noticed that grep prints out the matching lines containing your string, but you may also need the filenames of the files containing the string instead. You can use the -H option to narrow the output the filename followed by the line containing your search string, like so:
grep -H -r «myFunction» /var/www/html
This would output something like:
. your_file.php: line containing myFunction ..
To print out just the filename you can cut command like this to clean the output further: (Note the one after the f, not an L)
grep -H -r «myFunction» /var/www/html | cut -d: -f1
Источник
Searching string in file linux
The commands used are mainly grep and find.
Find string in file
grep string filename
grep name file.txt
Find string in file ignoring cases
grep string filename
grep -i name file.txt
Find string in current directory
grep string .
Find string recursively
grep -r string .
Find files that do not contain a string
grep -L string .
Find string recursively in only some specific files
grep string -r . —include=*.myextension
grep string -r . —include=*.
grep «name=Oscar» -r . —include=*.js
* if you specify —include it won’t look for the string in all files, just the ones included
Find string recursively in all files except the ones that contain certain extensions
grep string -r . —exclude=*.
grep «Serializable» -rl . —exclude=*.
Find string recursively all files including some extensions and excluding others
grep string -r . —include=*.myextension —exclude=*.myextension2
grep «my=string» -r . —include=*.
*It won’t look for the string in the js files.
Find string recursively in only some specific files and show their filename
grep string -rl . —include=*.myextension
grep «name=Oscar» -rl . —include=*.js
Find files and find a string in them using find
find . -name ‘*.extension’ -exec grep string +
find . -name ‘*.txt’ -exec grep Mytext <> +
find . -type f \( -name ‘*.htm’ -or -name ‘*.html’ \) -exec grep -i «mystring» <> +
Источник
How to use sed to find and replace text in files in Linux / Unix shell
Find and replace text within a file using sed command
The procedure to change the text in files under Linux/Unix using sed:
- Use Stream EDitor (sed) as follows:
- sed -i ‘s/old-text/new-text/g’ input.txt
- The s is the substitute command of sed for find and replace
- It tells sed to find all occurrences of ‘old-text’ and replace with ‘new-text’ in a file named input.txt
- Verify that file has been updated:
- more input.txt
Let us see syntax and usage in details.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | sed utility on Linux, macOS or Unix-like OS |
Est. reading time | 4 minutes |
Syntax: sed find and replace text
The syntax is:
sed ‘s/word1/word2/g’ input.file
## *bsd/macos sed syntax#
sed ‘s/word1/word2/g’ input.file > output.file
sed -i ‘s/word1/word2/g’ input.file
sed -i -e ‘s/word1/word2/g’ -e ‘s/xx/yy/g’ input.file
## use + separator instead of / ##
sed -i ‘s+regex+new-text+g’ file.txt
The above replace all occurrences of characters in word1 in the pattern space with the corresponding characters from word2.
Examples that use sed to find and replace
Let us create a text file called hello.txt as follows:
$ cat hello.txt
The is a test file created by nixCrft for demo purpose.
foo is good.
Foo is nice.
I love FOO.
I am going to use s/ for substitute the found expression foo with bar as follows:
sed ‘s/foo/bar/g’ hello.txt
Sample outputs:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Please note that the BSD implementation of sed (FreeBSD/MacOS and co) does NOT support case-insensitive matching. You need to install gnu sed. Run the following command on Apple Mac OS:
$ brew install gnu-sed
######################################
### now use gsed command as follows ##
######################################
$ gsed -i ‘s/foo/bar/g I ‘ hello.txt
$ cat hello.txt
sed command problems
Consider the following text file:
$ cat input.txt
http:// is outdate.
Consider using https:// for all your needs.
Find word ‘http://’ and replace with ‘https://www.cyberciti.biz’:
sed ‘s/ http:// / https://www.cyberciti.biz /g’ input.txt
You will get an error that read as follows:
Our syntax is correct but the / delimiter character is also part of word1 and word2 in above example. Sed command allows you to change the delimiter / to something else. So I am going to use +:
sed ‘s+ http:// + https://www.cyberciti.biz +g’ input.txt
Sample outputs:
How to use sed to match word and perform find and replace
In this example only find word ‘love’ and replace it with ‘sick’ if line content a specific string such as FOO:
sed -i -e ‘/FOO/s/love/sick/’ input.txt
Use cat command to verify new changes:
cat input.txt
Recap and conclusion – Using sed to find and replace text in given files
The general syntax is as follows:
## find word1 and replace with word2 using sed ##
sed -i ‘s/word1/word2/g’ input
## you can change the delimiter to keep syntax simple ##
sed -i ‘s+word1+word2+g’ input
sed -i ‘s_word1_word2_g’ input
## you can add I option to GNU sed to case insensitive search ##
sed -i ‘s/word1/word2/gI’ input
sed -i ‘s_word1_word2_gI’ input
See BSD(used on macOS too) sed or GNU sed man page by typing the following command:
man sed
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник