Linux finding word in files

Linux find text in files

Posted on February 12, 2016 By Nikola Stojanoski

If you need to find text in file or multiple files on a Linux system you can use grep (global regular expression print) in a very efficient way to do so. Here are few examples that I commonly use.

Find text in files into a directory

Use this command to find the text you are looking for within the directory

If you want to select only those lines containing matches that form whole words use the -w switch (–word-regexp). If you search for “word” this will NOT display words like someword, word123, etc.

If you don’t know the capitalization of words and want to ignore case distinctions use the -i switch (–ignore-case). If you search for “word” it will display Word, WORD, word, wORD, etc.

And the most often used command for me is recursive search -r switch (–recursive)

And finally few examples that i use the most

1. Find text in files recursive

Invoke -w (–word-regexp) and -r (–recursive) switch:

2. Find text in files case insensitive and recursive

Invoke -i (–ignore-case) and -r (–recursive) switch

3. Find multiple words in files

To find two different words you must use egrep

This days i use this to search trough logs, mostly apache, nginx and mail logs.

Also don’t forget to use zgrep. Zgrep invokes grep on compressed or gzipped files. All options specified are passed directly to grep.

For this we will use grep case insensitive because sometimes mail addresses can have Capital letters in the user First and Last Names.

This will output file and date when the mail was sent to the user, and than you can grep the time to get all the logs for that time:

You can now easy look at the log:

This ware just few command i usually use, look at the man page for more options.

Источник

How to Find a Specific String or Word in Files and Directories

Do you want to find all files that contain a particular word or string of text on your entire Linux system or a given directory. This article will guide you on how to do that, you will learn how to recursively dig through directories to find and list all files that contain a given string of text.

A simple way to work this out is by using grep pattern searching tool, is a powerful, efficient, reliable and most popular command-line utility for finding patterns and words from files or directories on Unix-like systems.

The command below will list all files containing a line with the text “check_root”, by recursively and aggressively searching the

Find a Word in Directory

Where the -R option tells grep to read all files under each directory, recursively, following symbolic links only if they are on the command line and option -w instructs it to select only those lines containing matches that form whole words, and -e is used to specify the string (pattern) to be searched.

Читайте также:  Что делать если компьютер пишет что не удалось запустить windows

You should use the sudo command when searching certain directories or files that require root permissions (unless you are managing your system with the root account).

To ignore case distinctions employ the -i option as shown:

If you want to know the exact line where the string of text exist, include the -n option.

Find String with Line Number

Assuming there are several types of files in a directory you wish to search in, you can also specify the type of files to be searched for instance, by their extension using the —include option.

This example instructs grep to only look through all .sh files.

In addition, it is possible to search for more than one pattern, using the following command.

Find Multiple Words in Files

That’s It! If you know any other command-line trick to find string or word in files, do share with us or ask any questions regarding this topic, use the comment form below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Find Files Containing Specific Text in Linux

Linux, regardless of the distro you use, comes with a number of GUI tools which allow searching for files. Many modern file managers support file searching right in the file list. However, most of them do not allow you to search inside a file’s contents. Here are two methods you can use to search for file contents in Linux.

I would like to share the methods I use myself.
The first method involves the grep utility, which exists in any distro, even in embedded systems built on busybox.

To find files containing specific text in Linux, do the following.

  1. Open your favorite terminal app. XFCE4 terminal is my personal preference.
  2. Navigate (if required) to the folder in which you are going to search files with some specific text.
  3. Type the following command:

Here are the switches:
-i — ignore text case
-R — recursively search files in subdirectories.
-l — show file names instead of file contents portions.

./ — the last parameter is the path to the folder containing files you need to search for your text. In our case, it is the current folder with the file mask. You can change it to the full path of the folder. For example, here is my command

Note: Other useful switches you might want to use with grep:
-n — show the line number.
-w — match the whole word.

Another method I use is Midnight Commander (mc), the console file manager app. Unlike grep, mc is not included by default in all Linux distros I’ve tried. You may need to install it yourself.

Find files containing specific text with mc

To find files containing some specific text using Midnight Commander, start the app and press the following sequence on the keyboard:
Alt + Shift + ?
This will open the search dialog.

Fill in the «Content:» section and press the Enter key. It will find all files with the required text.

You can place these files in the left or right panel using the Panelize option and copy/move/delete/view/do whatever you want them.

Midnight Commander is a very time-saving tool when it comes to search.

Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:

Share this post

About Sergey Tkachenko

Sergey Tkachenko is a software developer from Russia who started Winaero back in 2011. On this blog, Sergey is writing about everything connected to Microsoft, Windows and popular software. Follow him on Telegram, Twitter, and YouTube.

6 thoughts on “ Find Files Containing Specific Text in Linux ”

The code that you provided helped me. There are also another commands which I cannot remember to find text in files but this one is made it quickly. I have bookmarked this post for further usage. Thank you.

WHAT ABOUT WINDOWS?!

I use Total Commander for that.

Midnight Commander reminds me of XTree for DOS way, evidently, way way, back in the day!! 🙂 Anyone else remember!?

It reminds me of Norton Commander. Good days.

Источник

How to Find a Specific Word in a File on Linux

By default, most search tools look at file names, not file contents. However, the most famous GNU search program, grep , will look inside files with the correct flags. Here we will show you how you can find specific word(s) in a file on Linux.

Using grep to Find a Specific Word in a File

By default, grep searches through the contents of files as well as their file names. It’s included on the majority of Linux systems and is generally identical across distros. That said, smaller or less powerful Linux boxes might prefer to run a different command, like ack .

Depending on how the file is encoded, grep may not always be able to look inside. But for most text-based formats, grep can scan the text of the file for the specified pattern.

The -R flag sets grep to recursive mode, navigating through all the directories contained within the specified directory. The -w flag searches for whole word matches. This means that ‘red’ will match only ‘red’ surrounded by whitespace characters and not ‘redundant’ or ‘tired.’ The -e flag prefaces the pattern to search for. It supports regular expressions by default.

To speed up grep, you can use the —exclude and —include flags to limit the search to certain types of files. For example, —exclude=*.csv will not search within any files with the .csv extension. —include=*.txt , on the other hand, will only search within files with the .txt extension. The flag can be added immediately after the grep command, as shown below:

You can also exclude specified directories by following the format below:

This command will not search in any directories in the present working directory named dir1, dir2, or matching the pattern *_old, eliminating them from the search process. It will execute the specified recursive, full-word match search on all other files in the present working directory.

Using find to Find a Specific Word in a File

While the find command’s syntax is more complicated than grep, some prefer it.

This command will use find’s -exec flag to pass the found files to grep for searching. With a clever arrangement of syntax, you can use find’s faster file-system search to locate the specific file types you want to search within, then pipe them to grep in order to search inside the files.

Note that find only looks at filenames, not contents. That’s why grep is required to search file text and contents. The normal grep flags should be fully operational from within the -exec flag.

Using ack to Find a Specific Word in a File

The ack command is likely the fastest searching tool, but it’s not as popular as the above options. The command below will search within the current directory.

If you want to search within a specific file or directory, you can append that file or fully-qualified pathname to your search.

Conclusion

For most folks in most situations, grep is the best widely-available search tool. You can also look at other search tools, like RipGrep, for faster searching options

Alexander Fox is a tech and science writer based in Philadelphia, PA with one cat, three Macs and more USB cables than he could ever use.

Источник

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:

  1. Use Stream EDitor (sed) as follows:
  2. sed -i ‘s/old-text/new-text/g’ input.txt
  3. The s is the substitute command of sed for find and replace
  4. It tells sed to find all occurrences of ‘old-text’ and replace with ‘new-text’ in a file named input.txt
  5. Verify that file has been updated:
  6. 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

Источник

Читайте также:  Какие диски можно форматировать при установке windows
Оцените статью