How to find file in linux by name

Find a file by name using command-line

If it is already installed, new filename might not be postgis-2.0.0 anymore. Usually after installations via package managers, executables would be in one of the $PATH folders, try which postgis to see the location. If it returns nothing, only then you should manually look for file location.

9 Answers 9

Try find ~/ -type f -name «postgis-2.0.0» instead.

Using . will only search the current directory. ~/ will search your entire home directory (likely where you downloaded it to). If you used wget as root, its possible it could be somewhere else so you could use / to search the whole filesystem.

I get find: /Users/UserName//Library/Saved Application State/com.bitrock.appinstaller.savedState: Permission denied error. it appears on every execution of the command. How to get rid of it?

sudo find / -type d -name "postgis-2.0.0" 

The . means search only in the current directory, it is best to search everything from root if you really don’t know. Also, type -f means search for files, not folders. Adding sudo allows it to search in all folders/subfolders.

Your syntax for locate is correct, but you may have to run

first. For whatever reason, I never have good luck with locate though.

locate uses database of files and directories made by updatedb . So if you have downloaded a new file there is more chance that your updatedb has not updated the database of files and directories. You can use sudo updatedb before using locate utility program. updatedb generally runs once a day by itself on linux systems.

The other answers are good, but I find omitting Permission denied statements gives me clearer answers (omits stderr s due to not running sudo ):

find / -type f -iname "*postgis-2.0.0*" 2>/dev/null 
  • / can be replaced with the directory you want to start your search from
  • f can be replaced with d if you’re searching for a directory instead of a file
  • -iname can be replaced with -name if you want the search to be case sensitive
  • the * s in the search term can be omitted if you don’t want the wildcards in the search
find / -type f 2>/dev/null | grep "postgis-2.0.0" 

This way returns results if the search-term matches anywhere in the complete file path, e.g. /home/postgis-2.0.0/docs/Readme.txt

There are -regex and -iregex switches for searching with Regular Expressions , which would find the path mentions as well. Suggestion to find any item which is a file ( -type f ) then grep is more resource expensive. Permission denied happens when user doesn’t have access to files or folders, using sudo before find will allow find to see all files.

find is one of the most useful Linux/Unix tools.

Читайте также:  Linux read only filesystems

Try find . -type d | grep DIRNAME

  • where you can change ‘.'(look into the Current Directory) to ‘/'(look into the entire system) or ‘~/'(look into the Home Directory).
  • where you can change «-name» to «-iname» if you want no case sensitive.
  • where you can change «file_name«(a file that can start and end with whatever it is) to the exactly name of the file.

This should simplify the locating of file:

This would give you the full path to the file

Tree lists the contents of directories in a tree-like format. the -f tells tree to give the full path to the file. since we have no idea of its location or parent location, good to search from the filesystem root / recursively downwards. We then send the output to grep to highlight our word, postgis-2.0.0

$ find . -type f | grep IMG_20171225_*
Gives
./03-05—2018/IMG_20171225_200513.jpg
The DOT after the command find is to state a starting point,
Hence — the current folder,
«piped» (=filtered) through the name filter IMG_20171225_*

While find command is simplest way to recursively traverse the directory tree, there are other ways and in particular the two scripting languages that come with Ubuntu by default already have the ability to do so.

bash

bash has a very nice globstar shell option, which allows for recursive traversal of the directory tree. All we need to do is test for whether item in the ./**/* expansion is a file and whether it contains the desired text:

bash-4.3$ for f in ./**/* ;do [ -f "$f" ] && [[ "$f" =~ "postgis-2.0.0" ]] && echo "$f"; done ./testdir/texts/postgis-2.0.0 

Perl

Perl has Find module, which allows to perform recursive traversal of directory tree, and via subroutine perform specific action on them. With a small script, you can traverse directory tree, push files that contain the desired string into array, and then print it like so:

#!/usr/bin/env perl use strict; use warnings; use File::Find; my @wanted_files; find( sub< -f $_ && $_ =~ $ARGV[0] && push @wanted_files,$File::Find::name >, "." ); foreach(@wanted_files)
$ ./find_file.pl "postgis-2.0.0" ./testdir/texts/postgis-2.0.0 

Python

Python is another scripting language that is used very widely in Ubuntu world. In particular, it has os.walk() module which allows us to perform the same action as above — traverse directory tree and obtain list of files that contain desired string.

As one-liner this can be done as so:

$ python -c 'import os;print([os.path.join(r,i) for r,s,f in os.walk(".") for i in f if "postgis-2.0.0" in i])' ['./testdir/texts/postgis-2.0.0'] 

Full script would look like so:

#!/usr/bin/env python import os; for r,s,f in os.walk("."): for i in f: if "postgis-2.0.0" in i: print(os.path.join(r,i)) 

Источник

Find Files in Linux Using the Command Line

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

When you have to find a file in Linux, it’s sometimes not as easy as finding a file in another operating system. This is especially true if you are running Linux without a graphical user interface and need to rely on the command line. This article covers the basics of how to find a file in Linux using the CLI. The find command in Linux is used to find a file (or files) by recursively filtering objects in the file system based on a simple conditional mechanism. You can use the find command to search for a file or directory on your file system. By using the -exec flag ( find -exec ), matches, which can be files, directories, symbolic links, system devices, etc., can be found and immediately processed within the same command.

Читайте также:  Linux kernel build script

Find a File in Linux by Name or Extension

Use find from the command line to locate a specific file by name or extension. The following example searches for *.err files in the /home/username/ directory and all sub-directories:

find /home/username/ -name "*.err" 

Using Common find Commands and Syntax to Find a File in Linux

find expressions take the following form:

find options starting/path expression 
  • The options attribute will control the find process’s behavior and optimization method.
  • The starting/path attribute will define the top-level directory where find begins filtering.
  • The expression attribute controls the tests that search the directory hierarchy to produce output.

Consider the following example command:

find -O3 -L /var/www/ -name "*.html" 

This command enables the maximum optimization level (-O3) and allows find to follow symbolic links ( -L ). find searches the entire directory tree beneath /var/www/ for files that end with .html .

Basic Examples

Command Description
find . -name testfile.txt Find a file called testfile.txt in current and sub-directories.
find /home -name *.jpg Find all .jpg files in the /home and sub-directories.
find . -type f -empty Find an empty file within the current directory.
find /home -user exampleuser -mtime -7 -iname «.db» Find all .db files (ignoring text case) modified in the last 7 days by a user named exampleuser.

Options and Optimization for find

The default configuration for find will ignore symbolic links (shortcut files). If you want find to follow and return symbolic links, you can add the -L option to the command, as shown in the example above.

find optimizes its filtering strategy to increase performance. Three user-selectable optimization levels are specified as -O1 , -O2 , and -O3 . The -O1 optimization is the default and forces find to filter based on filename before running all other tests.

Optimization at the -O2 level prioritizes file name filters, as in -O1 , and then runs all file-type filtering before proceeding with other more resource-intensive conditions. Level -O3 optimization allows find to perform the most severe optimization and reorders all tests based on their relative expense and the likelihood of their success.

Command Description
-O1 (Default) filter based on file name first.
-O2 File name first, then file type.
-O3 Allow find to automatically re-order the search based on efficient use of resources and likelihood of success.
-maxdepth X Search current directory as well as all sub-directories X levels deep.
-iname Search without regard for text case.
-not Return only results that do not match the test case.
-type f Search for files.
-type d Search for directories.
Читайте также:  Скорость соединения интернета linux

Find a File in Linux by Modification Time

The find command contains the ability to filter a directory hierarchy based on when the file was last modified:

find / -name "*conf" -mtime -7 find /home/exampleuser/ -name "*conf" -mtime -3 

The first command returns a list of all files in the entire file system that end with the characters conf and modified in the last seven days. The second command filters exampleuser user’s home directory for files with names that end with the characters conf and modified in the previous three days.

Use grep to Find a File in Linux Based on Content

The find command can only filter the directory hierarchy based on a file’s name and metadata. If you need to search based on the file’s content, use a tool like grep . Consider the following example:

find . -type f -exec grep "example" '<>' \; -print 

This searches every object in the current directory hierarchy ( . ) that is a file ( -type f ) and then runs the command grep «example» for every file that satisfies the conditions. The files that match are printed on the screen ( -print ). The curly braces ( <> ) are a placeholder for the find match results. The <> are enclosed in single quotes ( ‘ ) to avoid handing grep a malformed file name. The -exec command is terminated with a semicolon ( ; ), which should be escaped ( \; ) to avoid interpretation by the shell.

How to Find and Process a File in Linux

The -exec option runs commands against every object that matches the find expression. Consider the following example:

find . -name "rc.conf" -exec chmod o+r '<>' \; 

This filters every object in the current hierarchy ( . ) for files named rc.conf and runs the chmod o+r command to modify the find results’ file permissions.

The commands run with the -exec are executed in the find process’s root directory. Use -execdir to perform the specified command in the directory where the match resides. This may alleviate security concerns and produce a more desirable performance for some operations.

The -exec or -execdir options run without further prompts. If you prefer to be prompted before action is taken, replace -exec with -ok or -execdir with -okdir .

How to Find and Delete a File in Linux

To delete the files that end up matching your search, you can add -delete at the end of the expression. Do this only when you are positive the results will only match the files you wish to delete.

In the following example, find locates all files in the hierarchy starting at the current directory and fully recursing into the directory tree. In this example, find will delete all files that end with the characters .err :

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on Monday, October 25, 2010.

Источник

Оцените статью
Adblock
detector