date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,344,375,382,000 |
Assuming that the grep tool should be used, I'd like to search for the text string "800x600" throughout the entire file system.
I tried:
grep -r 800x600 /
but it doesn't work.
What I believe my command should do is grep recursively through all files/folders under root for the text "800x600" and list the search result... |
I normally use this style of command to run grep over a number of files:
find / -xdev -type f -print0 | xargs -0 grep -H "800x600"
What this actually does is make a list of every file on the system, and then for each file, execute grep with the given arguments and the name of each file.
The -xdev argument tells find ... | How to search text throughout entire file system? |
1,344,375,382,000 |
I am trying to find the largest file in a directory recursively. If there is a subdirectory inside of that directory the function needs to go inside that directory and check to see if the largest file is there. Once the largest file is found the output is displayed with the relative path name and the name and size of ... |
use find (here assuming GNU find) to output file names with the file size. sort. print out the largest one.
find . -type f -printf "%s\t%p\n" | sort -n | tail -1
That assumes file paths don't contain newline characters.
Using a loop in bash with the GNU implementation of stat:
shopt -s globstar
max_s=0
for f in **; ... | Finding largest file recursively |
1,344,375,382,000 |
What concise command can I use to find all files that do NOT contain a text string?
I tried this (using -v to invert grep's parameters) with no luck:
find . -exec grep -v -l shared.php {} \;
Someone said this would work:
find . ! -exec grep -l shared.php {} \;
But it does not seem to work for me.
This page has this ... |
find . -type f | xargs grep -H -c 'shared.php' | grep 0$ | cut -d':' -f1
OR
find . -type f -exec grep -H -c 'shared.php' {} \; | grep 0$ | cut -d':' -f1
Here we are calculating number of matching lines(using -c) in a file if the count is 0 then its the required file, so we cut the first column i.e. filename from... | How can I find all files that do NOT contain a text string? |
1,344,375,382,000 |
How can I list recursively all files that were changed between 22.12.2011 and 24.12.2011?
|
Generally speaking, when you're looking for files in a directory and its subdirectories recursively, use find.
The easiest way to specify a date range with find is to create files at the boundaries of the range and use the -newer predicate.
touch -t 201112220000 start
touch -t 201112240000 stop
find . -newer start \! ... | How to list files that were changed in a certain range of time? |
1,344,375,382,000 |
I need to delete all compiled data:
directories called build,
directories called obj,
*.so files.
I wrote a command
find \( -name build -o -name obj -o -name *.so \) -exec rm -rf {} \;
that goes through all the directories recursively and deletes all I need.
Why do I have such an output at the end?
Maybe I should ... |
Use -prune on the directories that you're going to delete anyway to tell find not to bother trying to find files in them:
find . \( -name build -o -name obj -o -name '*.so' \) -prune -exec rm -rf {} +
Also note that *.so needs to be quoted as otherwise it may be expanded by the shell to the list of .so files in the c... | Delete files and directories by their names. No such file or directory |
1,344,375,382,000 |
It often happens that I want to apply an operation recursively. Some commands, such as grep, use a lowercase r to indicate recursion. For example
grep -r foo .
Other commands seem to prefer an uppercase R:
chmod -R 755 .
I am constantly getting these the wrong way around and forgetting which is which. Is there any l... |
Most POSIX commands that have recursive directory traversal option (ls, chmod, chgrp, chmod, cp, rm) have -R for that.
rm also has -r because that's what it was initially, long before POSIX.
Now, the behaviour varies when symlinks are found in walking down the tree. POSIX tried to make things consistent by adding the... | The difference between -r and -R |
1,344,375,382,000 |
if I want to count the lines of code, the trivial thing is
cat *.c *.h | wc -l
But what if I have several subdirectories?
|
The easiest way is to use the tool called cloc. Use it this way:
cloc .
That's it. :-)
| Counting lines of code? |
1,344,375,382,000 |
I'm wanting to find all directories with a specific string so I can do another find on the files contained within.
So I don't want to waste time on ./my-search-term/dir/my-search-term etc.
How can I stop recursing when I've found the first my-search-term directory?
|
The -prune action makes find not recurse into the directory. You can combine it with another action such as -exec (the order of -prune and -exec doesn't matter, as long as -prune is executed either way).
find . -name my-search-term -prune -exec find {} … \;
Note that nesting find inside a find -exec can be a little p... | How do I stop a find from descending into found directories? |
1,344,375,382,000 |
I have a folder SOURCE that contains several sub-level folders, each with its own files.
I want to copy this folder in a new folder COPY where I need to copy the directory structure but keep the files as symbolic links to the original files in SOURCE and its subfolders.
|
Here's the solution on non-embedded Linux and Cygwin:
cp -as SOURCE/ COPY
Note that SOURCE must be an absolute path and have a trailing slash. If you want to give a relative path, you can use
cp -as "$(pwd)/SOURCE/" COPY
| How to copy a folder structure and make symbolic links to files? |
1,344,375,382,000 |
This answer reveals that one can copy all files - including hidden ones - from directory src into directory dest like so:
mkdir dest
cp -r src/. dest
There is no explanation in the answer or its comments as to why this actually works, and nobody seems to find documentation on this either.
I tried out a few things. Fi... |
The behaviour is a logical result of the documented algorithm for cp -R. See POSIX, step 2f:
The files in the directory source_file shall be copied to the directory dest_file, taking the four steps (1 to 4) listed here with the files as source_files.
. and .. are directories, respectively the current directory, and ... | cp behaves weirdly when . (dot) or .. (dot dot) are the source directory |
1,344,375,382,000 |
How to download a full website, but ignoring all binary files.
wget has this functionality using the -r flag but it downloads everything and some websites are just too much for a low-resources machine and it's not of a use for the specific reason I'm downloading the site.
Here is the command line i use: wget -P 20 -r ... |
I've tried a totally different approach is to use Scrapy, however it has the same problem! Here's how I solved it: SO: Python Scrapy - mimetype based filter to avoid non-text file downloads?
The solution is to setup a Node.js proxy and configure Scrapy to use
it through http_proxy environment variable.
What the pro... | wget - How to download recursively and only specific mime-types/extensions (i.e. text only) |
1,344,375,382,000 |
I have a directory in which I would like to list all the content (files and sub directories) without showing the symbolic links. I am using GNU utilities on Linux. The ls version is 8.13.
Example:
Full directory listing:
~/test$ ls -Gg
total 12
drwxrwxr-x 2 4096 Jul 9 10:29 dir1
drwxrwxr-x 2 4096 Jul 9 10:29 dir2
dr... |
For the stated question you can use find:
find . -mindepth 1 ! -type l
will list all files and directories in the current directory or any subdirectories that are not symlinks.
mindepth 1 is just to skip the . current-directory entry. The meat of it is the combination of -type l, which means "is a symbolic link", and... | ls content of a directory ignoring symlinks |
1,344,375,382,000 |
Recursively iterating through files in a directory can easily be done by:
find . -type f -exec bar {} \;
However, the above does not work for more complex things, where a lot of conditional branches, looping etc. needs to be done. I used to use this for the above:
while read line; do [...]; done < <(find . -type f)
... |
Yet another use for safe find:
while IFS= read -r -d '' -u 9
do
[Do something with "$REPLY"]
done 9< <( find . -type f -exec printf '%s\0' {} + )
(This works with any POSIX find, but the shell part requires bash. With *BSD and GNU find, you can use -print0 instead of -exec printf '%s\0' {} +, it will be slightly ... | Recursively iterate through files in a directory |
1,344,375,382,000 |
On our Solaris server I'm finding that grep -r doesn't work, which is the usual way that I use grep. It seems that egrep has the same behavior.
Given that I have no control over the machine, is there a way to have grep perform a recursive search? Or do I need to pipe the output of find into grep?
|
I'm not familiar with Solaris, but if you're switching from GNU/linux to Solaris you'll find most of the commands will behave slightly different. The GNU version of Unix tools have additional features missing in "proprietary" Unixes.
You can download GNU grep(s) here then compile and install.
If you do have root acces... | Recursive search doesn't work for grep on solaris |
1,344,375,382,000 |
How do I recursively add(or touch) a file into the current directory, as well as all sub-directories?
For example,
I would like to turn this directory tree:
.
├── 1
│ ├── A
│ └── B
├── 2
│ └── A
└── 3
├── A
└── B
└── I
9 directories, 0 files
into
.
├── 1
│ ├── A
│ │ └── file
│ ├── B
│... |
How about:
find . -type d -exec cp file {} \;
From man find:
-type c
File is of type c:
d directory
-exec command ;
Execute command; All following arguments to find are taken
to be arguments to the command until an argument consisting
of `;' is enco... | Recursively add a file to all sub-directories |
1,344,375,382,000 |
This is pretty basic, I have a folder with several subfolders of JS files and i want to run Google's Clojure compiler on all of the files in those folders. The command to process a single file is as follows:
java -jar compiler.jar --js filename.js --js_output_file newfilename.js
How do I modify this to run on every J... |
You can use find:
find . -name "*.js" -exec java -jar compiler.jar --js {} --js_output_file new{} \;
| How do I run a command on multiple files |
1,344,375,382,000 |
This is a more general question about 'chmoding' recursively.
I have this script which at some point needs to change the permissions recursively in a folder which has a few hundred thousand files.
There are new files added in that folder every day, but the ones that are already there have the permissions already set a... |
chmod might or might not change the permissions of files that are already set to what you want, but if not, it would still need to check them to see what their current permissions are[0]. With hundreds of thousands of files, I don't think it would matter either way; the time is most likely being spent by the tools sta... | chmod recursive permission on thousands of files |
1,344,375,382,000 |
I found if I search using grep without specifying a path, like grep -r 'mytext' it takes infinitely long. Meanwhile if I search with path specified grep -r 'mytext' . it instantly finds what I need. So, I'm curious, in first form, in which directory does grep search?
UDATE: grep version: grep (GNU grep) 2.10
|
Actually it doesn't search anywhere. It waits for input from standard input.
Try this:
beast:~ viroos$ grep foo
when you type line containing "foo" and hit enter this line will be repeated otherwise cursor will be moved to new line but grep won't print anything.
| Where does grep -r search by default? |
1,344,375,382,000 |
I want to remove the contents of a zfs datasets subdir. It's a large amount of data. For the pool "nas", the path is /nas/dataset/certainFolder
$ du -h -d 1 certainFolder/
1.2T certainFolder/
Rather than me have to wait for rm -rf certainFolder/ can't I just destroy the handle to that directory so its overwrite-... |
Tracking freed blocks is unavoidable in any decent file system and ZFS is no exception. There is however a simple way under ZFS to have a nearly instantaneous directory deletion by "deferring" the underlying cleanup. It is technically very similar to Gilles' suggestion but is inherently reliable without requiring extr... | Bulk remove a large directory on a ZFS without traversing it recursively |
1,344,375,382,000 |
I'm trying to monitor my /tmp folder for changes using inotifywatch:
sudo inotifywatch -v -r /tmp
After creating couple of files (touch /tmp/test-1 /tmp/test-2), I'm terminating inotifywatch (by Ctrl-C which shows me the following statistics:
Establishing watches...
Setting up watch(es) on /tmp
OK, /tmp is now being... |
This is due to the way you're using inotifywatch, and the way the tool itself works. When you run inotifywatch -r /tmp, you start watching /tmp and all the files that are already in it. When you create a file inside /tmp, the directory metadata is updated to contain the new file's inode number, which means that the ch... | Why doesn't inotifywatch detect changes on added files? |
1,344,375,382,000 |
Let's say I need to find the function GetTypes() in all C# source file (.cs) the directories/subdirectories.
I used grep -rn GetTypes *.cs, but I got an error with grep: *.cs: No such file or directory. I had to use grep -rn GetTypes *, but in this case it shows all the files not *.cs only.
What command do I need to u... |
If your shell is bash ≥4, put shopt -s globstar in your ~/.bashrc. If your shell is zsh, you're good. Then you can run
grep -n GetTypes **/*.cs
**/*.cs means all the files matching *.cs in the current directory, or in its subdirectories, recursively.
If you're not running a shell that supports ** but your grep suppor... | Find a string only in a specific file inside subdirectories |
1,344,375,382,000 |
I'd like to recursively rename all files and folders (sub-folders) to uppercase.
I found some scripts that will do it to lowercase, but I don't know how to change them so it will do it the other way around (lower to upper).
The script that I found and works for lowercase, but I didn't knew how to modify is:
rename 'y/... |
Note that you're using the Perl script called rename distributed by Debian and derivatives (Ubuntu, Mint, …). Other Linux distributions ship a completely different, and considerably less useful, command called rename.
y/A-Z/a-z/ translates each character in the range A through Z into the corresponding character in the... | How can I use rename to recursively rename everyting to uppercase |
1,344,375,382,000 |
I'm wondering about direction of recursion in general and rm specifically.
rm recursion only works downwards correct?
Running: sudo rm -R *.QTFS will delete all *.QTFS files in current directory and its children, correct?
current directory as displayed by ls -lha also contains . and .. links for the lack of a better ... |
rm recursion only works downwards correct?
rm -r x y will delete x and y and everything inside them (if they are directories), but not their parents or anything outside them.
Running: sudo rm -R *.QTFS will delete all *.QTFS files in current directory and its children, correct?
No. It will delete all files named *... | Why doesn't recursion go upwards with rm? |
1,344,375,382,000 |
I use vim a lot, and my area has power failure a lot. So the resultant is I get many *.swp files scattered over my PC.
I want an alias of rm command that removes all files with either .swp, ~, .netrwhist, .log or .bak extensions system wide (or atleast in my home directory). The command should delete the files system ... |
This will delete all the files with a name ending in .swp, ~, .netrwhist, .log or .bak anywhere under your home directory. No prompt, no confirmation, no recovery, the files are gone forever.
find ~ -type f \( -name '*.swp' -o -name '*~' -o -name '*.bak' -o -name '.netrwhist' \) -delete
(I purposefully omit *.log bec... | Locate and delete all temporary files in user directory |
1,344,375,382,000 |
I have a host that I can only access with sftp, scp, and rsync-- no ssh. I have a large tree of directories that I want to delete, but my sftp client apparently does not support recursive rms or rmdirs. In the help screen, it shows I can do recursive puts, but that doesn't help me.
How can I delete my files?
|
You can use the lftp client to do this. The the -r option to lftp rm recursively deletes directories and files.
$ lftp -u <user>,<pass> <server>
lftp> rm -r <directory>
References
lftp main website
| recursive delete with sftp? |
1,344,375,382,000 |
In Windows, if I wanted to find a string across all files in all subdirectories, I would do something like
findstr /C:"the string" /S *.h
However, in Linux (say, Ubuntu) I have found no other way than some piped command involving find, xargs, and grep (an example is at this page: How can I recursively grep through su... |
GNU grep allows searching recursively through subdirectories:
grep -r --include='*.h' 'the string' .
| Finding a substring in files across subdirectories with a single built-in command? |
1,344,375,382,000 |
I'm trying to create a compressed tarball that contains all PDF files that exist in one of my directories. The directory structure needs to be retained. Empty directories are not needed, but I really don't care if they're there.
For example, say I had a directory that looked like this:
dir
dir/subdir1
dir/subdir1/subs... |
This will list all the PDFs:
$ find dir/ -name '*.pdf'
./dir/subdir2/subsubdir1/document.pdf
./dir/subdir3/another-document.pdf
You can pipe that to xargs to get it as a single space-delimited line, and feed that to tar to create the archive:
$ find dir/ -name '*.pdf' | xargs tar czf dir.tar.gz
(This way omits the e... | Tar up all PDFs in a directory, retaining directory structure |
1,344,375,382,000 |
I have this kind of directory tree that is obtained from unzipping a zip file:
x -> y -> z -> run -> FILES AND DIRECTORIES HERE
So there are 4 directories, 3 of whom are empty of files (x, y, z) and only contain 1 sub-directory, and there is the directory I am interested in, named "run".
I want to move the "run" dir... |
what about
find . -type d -name run -exec mv {} /path/to/X \;
where
/path/to/X is your destination directory
you start from this same place.
then use other answer to remove empty directories.
(on a side note there is a --junk-paths option in zip, either when zipping or unzipping)
| How to extract a specifically named folder from a recursive directory, delete the others? |
1,344,375,382,000 |
Imagine a source tree. There are xml files everywhere.
But since there is a XYZ.xml at the root of this tree it won't find my xml files.
find -iname *.xml
returns
./XYZ.xml
instead of
./XYZ.xml
./a/b/c/bob.xml
./b/d/top.xml
|
find -iname '*.xml'
Otherwise, your shell expands *.xml to XYZ.xml, and the command that actually gets executed is
find -iname XYZ.xml
The reason it works if there are no XML files in the current directory is that shells generally leave wildcards unexpanded if they don't match anything. In general, any time you wan... | find not recursive when given a pattern on the command line |
1,489,601,181,000 |
Suppose I have this structure for folder0 and subfolders and files in it.
folder0
subfolder01
file011
file012
subfolder02
file021
file01
file02
I want to copy all files in main folder folder0 to somewhere else, such that all file be in one directory? How Can I do tha... |
Use find:
find folder0 -type f -exec cp {} targetfolder \;
With GNU coreutils you can do it more efficiently:
find folder0 -type f -exec cp -t targetfolder {} +
The former version runs cp for each file copied, while the latter runs cp only once.
| How to copy "just files" recursively |
1,489,601,181,000 |
I'm relatively new to Bash and am trying to do something that on the surface seemed pretty straightforward - run find over a directory hierarchy to get all of the *.wma files, pipe that output to a command where I convert them to mp3 and save the converted file as .mp3. My thinking was that the command should look lik... |
As other answers have already identified, ${f%.*} is expanded by the shell before it runs the xargs command. You need this expansion to happen once for each file name, with the shell variable f set to the file name (passing -I f doesn't do that: xargs has no notion of shell variable, it looks for the string f in the c... | Manipulate file name piped from find command |
1,489,601,181,000 |
I have a top folder with many sub-folders. It's named "a". There are many .png and .jpg files in there. I'd like to recursively copy "a" into a new folder "b", but only copy the .png and .jpg files. How do I achieve that?
|
find a \( -name "*.png" -or -name "*.jpg" \) -exec cp {} b \;
| Copy only certain file types from a folder structure to another |
1,489,601,181,000 |
I want to generate a list of files that have:
Same name
Different content
in a directory (including all children directories and content).
How to do? Bash, perl, anything is fine.
So, two files with the same name and same content should not show up.
|
Update: fixed a typo in the script: changed print $NF to print $3; also tidied things up, and added some comments.
Assuming file names do not contain \n, the following prints out a sorted list which breaks (as in: section control breaks) at unique file name, unique md5sum, and shows the corresponding group of file p... | Find files with same name but different content? |
1,489,601,181,000 |
Given the following directory tree:
.
├── d1
│ └── workspace
├── d2
│ └── workspace
├── d3
│ └── workspace
├── d4
│ └── workspace
└── d5
└── workspace
I need to set the permissions for all workspace directories as below:
chmod -R 774 d1/workspace
chmod -R 774 d2/workspace
...
How can I do the above... |
You can use wildcards on the top level directory.
chmod 774 d*/workspace
Or to make it more specific you can also limit the wildcard, for example to d followed by a single digit.
chmod 774 d[0-9]/workspace
A more general approach could be with find.
find d* -maxdepth 1 -name workspace -type d -exec chmod 774 "{}" \;... | How to chmod only on subdirectories? |
1,489,601,181,000 |
rsync -avi --delete --modify-window=1 --no-perms --no-o --no-g
~/Documents/Stuff/ /media/user/PC/Stuff;;
i.e. to not copy sub-directories from the source directory?
|
You can add option --exclude='*/' to your rsync options to prevent syncing of directories.
| How do I make this rsync command non-recursive? |
1,489,601,181,000 |
I want to compare the contents of two directories, recursively, showing which files are missing from one or the other, and which files have different content. But I don't want output on the differences within the files, just whether they are different or not. There won't be any links to worry about.
I hope this isn't ... |
Usually this looks already good:
diff -rq dirA dirB
| Recursively compare directories with summary on different contents without examining file contents' differences |
1,489,601,181,000 |
I'm running zsh on Linux under setopt extended_glob ksh_glob glob_dots. I'm looking for something easy to type on the command line, with no portability requirements. I'm looking at a source code tree, with no “weird” file names (e.g. no \ in file names, no file name beginning with -).
Either of the following commands ... |
Zsh's extended glob operators support matching over / (unlike ksh's, even in zsh's implementation). Zsh's **/ is a shortcut for (*/)# (*/ repeated 0 or more times). So all I need to do is replace that * by ^.svn (anything but .svn).
print -l (^.svn/)#
Neat!
| Excluding a directory name in a zsh recursive glob |
1,489,601,181,000 |
I wanted to delete files and folder recursively from a particular folder so I ran this command from that folder
rm -rf *
I assumed it would delete all files/directories under the current directory recursively. Something bad happened after that (my server is down, not even getting ping response).
|
Don't forget the possibility that the server being unreachable after the rm command had nothing to do with that. It could be a coincidence!
Most likely though, the current working directory was not what you thought, when the command was issued.
Were you root when doing this?
This is what happens when issuing the comma... | Does rm -rf * delete files recursively from the current directory or parent/root directory? |
1,489,601,181,000 |
In windows you get a count of the number of subdirectories within a directory.Is there any equivalent on Linux ?
I'd like it to count recursively & Not stop at a single level.
|
Use find to count all directories in a tree starting from current directory:
find . -mindepth 1 -type d | wc -l
Note, that -mindepth is required to exclude current directory from the count.
You can also limit depth of search with -maxdepth option like this:
find . -mindepth 1 -maxdepth 1 -type d | wc -l
More find op... | How to find number of Subdirectories under a given directory [duplicate] |
1,489,601,181,000 |
I have Zip files, that might look like this:
$ zipinfo -1 zip.zip
doc.doc
dotx.dotx
xls.xls
ppt.ppt
txt.txt
c.c
subdir/subdir2/doc.doc
subdir/xls.xls
subdir/ppt.ppt
subdir/c.c
subdir/txt.txt
subdir/subdir2/
subdir/
I want it to print all the *.doc files, but zipinfo -1 zip.zip *.doc only prints the .doc files in the ... |
zipinfo -1 zip.zip '*.doc'
works for me, displaying all files in sub-directories. I think you are forgetting the quotes around the *.doc. Without the quotes, the *.doc expands to all .doc files in the current directory, and then that is passed to zipinfo as the search pattern. So if you have an unzipped version of th... | How can I list all *.doc files in a Zip archive, including files in subdirectories? |
1,489,601,181,000 |
I have this idea of running a bash script to check some conditions and using ffmpeg to convert all the videos in my directory from any format to .mkv and it is working great!
The thing is, I did not know that a for file in loop does not work recursively (https://stackoverflow.com/questions/4638874/how-to-loop-through-... |
You've got this code:
for file in *.mkv *avi *mp4 *flv *ogg *mov; do
target="${file%.*}.mkv"
ffmpeg -i "$file" "$target" && rm -rf "$file"
done
which runs in the current directory. To turn it into a recursive process you have a couple of choices. The easiest (IMO) is to use find as you suggested. The syntax for... | Converting `for file in` to `find` so that my script can apply recursively |
1,489,601,181,000 |
Question about wget, subfolder, and index.html.
Let's say I am inside "travels/" folder and this is in "website.com": "website.com/travels/".
Folder "travels/" contains a lot of files and other (sub)folders: "website.com/travels/list.doc" , "website.com/travels/cover.png" , "website.com/travels/[1990] America/" , "web... |
This command will download only images and movies from a given website:
wget -nd -r -P /save/location -A jpeg,jpg,bmp,gif,png,mov "http://www.somedomain.com"
According to wget man:
-nd prevents the creation of a directory hierarchy (i.e. no directories).
-r enables recursive retrieval. See Recursive Download for mor... | Wget: downloading files selectively and recursively? |
1,489,601,181,000 |
I've been using the following command to list the most recently updated files (recursively) within a specific directory and order by modification time:
$ stat --printf="%y %n\n" $(ls -tr $(find * -type f))
However, within the hierarchy, there is one directory that is full of files that get updated on a near minute-b... |
You don't need that extra ls -tr. This is equivalent to your command and faster:
find . -type f | xargs stat --printf="%y %n\n" | sort -n
Something like this will exclude a subdirectory of files:
find . -type f ! -path './directory/to/ignore/*' \
| xargs stat --printf="%y %n\n" \
| sort -n
This will still ... | Excluding a specific directory using a recursive 'ls' |
1,489,601,181,000 |
Trying to get my id3 tags cleaned up and am loving id3v2 on the command line -- but I've been using it only with a *.mp3 wildcard and want to explore if there's a way to use it recursively so I can batch all of my MP3s. There doesn't seem to be an option to use it recursively.
I'm pretty sure all you awesome command ... |
You should be able to do this in a single line, with something like this:
find . -name '*.mp3' -execdir id3v2 --remove-frame "COMM" '{}' \; -execdir id3v2 --remove-frame "PRIV" '{}' \; -execdir id3v2 -s '{}' \;
The {} are substituted for the current filename match. Putting them in quotes ('') protects them from the s... | id3v2 used recursively at command line? |
1,489,601,181,000 |
Could someone explain why this happens?
Most specifically:
Why is one 1's content copied to f?
And why is f copied to g?
$ tree
.
0 directories, 0 files
$ mkdir 1
$ mkdir 2
$ touch 1/a
$ touch 1/b
$ mkdir 1/c
$ touch 1/c/x
$ tree
.
├── 1
│ ├── a
│ ├── b
│ └── c
│ └── x
└── 2
3 directories, 3 files
$... |
For cp, the destination is the last argument on the command line. You have specified 2/g as the last argument.
Before cp is executed, the command parameters are expanded. 1/* expands to 1/a 1/b 1/c. 2/* expands to 2/f 2/g. The final executed command is cp -r 1/a 1/b 1/c 2/f 2/g, which will copy all the arguments (exce... | Strange behaviour in recursive copy |
1,489,601,181,000 |
I just copied all the files/subdirectories in my home directory to another user's home directory.
Then I did a recursive chown on his home directory, so that he became the owner of all his files/subdirectories.
The last thing I need to do is a recursive chgrp on his home directory, so that his username will be the gro... |
Use find to exclude anything owned by group docker; starting from the target home directory:
find . ! -group docker -exec chgrp newgroup {} +
replacing newgroup as appropriate.
Alternatively, look for anything owned by your group:
find . -group oldgroup -exec chgrp newgroup {} +
replacing oldgroup and newgroup as ap... | How do I recursively run "chgrp" without changing the group if it matches a specific group? |
1,489,601,181,000 |
I need to create an md5 hash of every directory and file inside of one main directory. The only thing that is keeping me from success is figuring out a way around files with a space in the path.
I am using find for the recursive listing (I have read that find is the best way of doing this):
c5-26-1# find /root/newdir
... |
xargs is rarely useful, because it expects input quoted in a highly peculiar way that no common tool produces. And as you've noticed mycommand $(find …) is no good, because it first concatenates all the file names and then splits at whitespace.
Use the -exec primary of find to make it execute md5 with no intervening s... | create md5 hash from a recursive file listing when some paths have spaces |
1,489,601,181,000 |
I have a hypothetical situation:
Let us say we have two strace processes S1 & S2, which are simply monitoring each other.
How can this be possible?
Well, in the command-line options for strace, -p PID is the way to pass the required PID, which (in our case) is not yet known when we issue the strace command. We could ... |
I will answer for Linux only.
Surprisingly, in newer kernels, the ptrace system call, which is used by strace in order to actually perform the tracing, is allowed to trace the init process. The manual page says:
EPERM The specified process cannot be traced. This could be because
the tracer has insuff... | How can strace monitor itself? |
1,489,601,181,000 |
I have the following directory structure:
test/
test/1/
test/foo2bar/
test/3/
I want to compress directory "test" excluding everything which is in subdirectories (depth not predefined), which include strings "1" or "2" in them. In bash shell, i want to use find and feed its output to tar. I first test find:
find test... |
To expand on what @cuonglm said, tar by default operates recursively. If you pass it a directory name, it will archive the contents of that directory.
You could modify your find command to return only the names of files, not directories...
find test/ -type f -not -path "*1*" -not -path "*2*" |
tar -czvf test.tar.gz... | filter in "find" ignored when output fed to tar |
1,489,601,181,000 |
I want to copy a directory into another directory.
For example, cp -r dir1 dir2 copies the contents of dir1 into dir2. I want to copy dir1 itself into dir2 so that if I ls dir2 it will output dir1 and not whatever was inside of dir1.
|
Just do as you did:
cp -r dir1 dir2
and you will have dir1 (with its content as well) inside dir2. Try if you don't believe ;-).
The command that would copy content of dir1 into dir2 is:
cp -r dir1/* dir2
| Copy directory not just the contents |
1,489,601,181,000 |
I'm using Solaris 10 and have two grep versions one in /usr/bin and one in /usr/xpg4/bin. I have been searching for an answer on how to search for text within files within sub folders of a parent directory using grep. All answers talk about -r or -R switches which I do not have available with my version of grep.
|
The standard (POSIX) syntax is:
find /path/to/parent -type f -exec grep 'XXX' /dev/null {} +
(the /dev/null is to make sure grep always prints a file name). That will work on all POSIX systems including Solaris. The only known post-90s systems where that's known not to work is old (very old now) GNU systems.
GNU init... | How do I use grep to find a text string in files in sub folders of a parent folder without -r switch |
1,489,601,181,000 |
I'm working on a website migration. I have a scrape of the site, with all the files and directory structure as you would see them in the URL. I want to pull all images, maintaining the directory structure, and copy them into a new place.
For instance, if I have
/content1/index.php
/content1/page2.php
/content1/images... |
Try this command (find and cp with --parent option):
find /source -regextype posix-extended -regex '.*(gif|jpg)' \
-exec cp --parents {} /dest \; -print
| recursively copy only images and preserve path |
1,489,601,181,000 |
I'd like to use wget to recursively download a web page. By recursively I mean all the other files it might point to should be downloaded as well. The reason for that is that I'd like to be able to reasonably see its content offline.
The webpage I need to download also links to other pages on the same website, and I w... |
Try:
wget -r -np -k -p http://www.site.com/dir/page.html
The args (see man wget) are:
r Recurse into links, retrieving those pages too (this has a default max depth of 5, can be set with -l).
np Never enter a parent directory (i.e., don't follow a "home" link and mirror the whole site; this will prevent going above ... | How to recursively download a web page and its linked content from a URL? |
1,489,601,181,000 |
I just can not get it right.
Script takes two arguments, target and command. Valid targets are specified within an array. If target is 'all', script should iterate through all targets.
#!/bin/bash
# recur.sh
targets=('aaa' 'bbb' 'ccc' 'ddd')
if [ "$1" == "all" ] ; then
for i in $targets ; do
echo $2" -->... |
The problem isn't in the recursion, it's in the looping over the items. If you try this as above, you don't get what you expect:
$ targets=(aaa bbb ccc ddd)
$ for i in $targets; do echo $i; done
aaa
To loop over the array, you need to generate a list of the items in the array, as per,eg, this link:
So you have
#!/bi... | bash script calling itself with different arguments |
1,489,601,181,000 |
Is there an easy way to search inside 1000s of files in a complex directory structure to find files which contain a specific string within the file?
|
grep -H -R searchstring /directory
may want to redirect the results to a file (or tee)
You may also want to look at ack
| Searching for string in files |
1,489,601,181,000 |
How can I find a word in specific files matching a pattern. e.g. searching for version in CMake* files recursively found in the current directory.
|
If you want to see the file name and line number, POSIXly:
find . -name 'CMake*' -type f -exec grep -nF /dev/null version {} +
(you don't want to use ; here which would run one grep per file). That's the standard equivalent of the GNUism:
find . -name 'CMake*' -type f -print0 | xargs -r0 grep -nHF {} +
find (in the ... | How to search in specific files matching a pattern |
1,489,601,181,000 |
I need to essentially merge changes on two trees, applying the changes from branch 2 to branch 1. I have trees like this:
media
├── cd
│ ├── 0
│ │ ├── file1
│ │ ├── file2
│ │ └── file3
│ ├── 1
│ │ ├── file1
│ │ ├── file2
│ │ └── file3
│ └── 2
│ ├── file1
│ ├── file2
│ └─... |
Why not use rsync instead?
rsync -a /branch2/media/ /branch1/media/
The reason why mv can't move /branch2/media/cd/ to /branch1/media is because /branch1/media already has a cd/ in it. mv refuses to clobber non-empty directories.
| How can I move a directory onto an existing directory? |
1,489,601,181,000 |
I once saw a colleague uses a tool which allows to use ** to represent any directories. For example: if a file called myfile.java sits deep inside:
src/main/com/mycompany/product/store/myfile.java
A command in the parent of src directory:
ls **/myfile.java
can list the file.
Can anyone tell me what tool it is? What ... |
In bash ≥4.0, turn on the globstar option.
$ shopt -s globstar
$ echo pylib/**/pyerector.py
pylib/pyerector.py pylib/pyerector/pyerector.py
You can read more about it in the manpage.
In zsh, this is available out of the box.
In ksh93, activate it with set -o globstar.
In plain sh or bash ≤3.x, this is not available.
| What is the tool that allows me to specify arbitrary directories using ** |
1,489,601,181,000 |
I was creating a symbolic link to folder1/folder2 in home-folder. But I accidentally did:
ln -s folder1/folder2
while in folder2 instead of in home-folder. So I ended up accidentally creating a sort-of-recursive link.
Now I can't remove this link:
rm folder1/folder2
gives the error message 'folder1/folder2' Is a dir... |
When you have a symbolic link to a directory, if you add a trailing slash to the name then you get the directory itself, not the symlink. As a result:
rm link/
will try to remove the directory. What you want is to specify the link name only without a trailing slash:
rm link
That should enable you to remove the lin... | Accidentally created symbolic link to a folder in that folder |
1,489,601,181,000 |
So I've arrived at the conclusion that for recursively replacing all instances of a string in directory (only for .java extensions files) I need to use
find . -type f -name "*.java" -exec sed -i 's/original/result/g' {} +
However what do I do if the string I am trying to replace contains /?
For example I want to rep... |
Escape the slash, writing \/
You could also do:
perl -pi -e 's!original!result!g' *java
using ! as a delimiter instead of /. This is a bit shorter than using find & sed.
| Replace string in multiple files using find and sed |
1,489,601,181,000 |
I need to pass a user and a directory to a script and have it spit out a list of what folders/files in that directory that the user has read access to. MS has a tool called AccessChk for Windows that does this but does something like this exist on the Unix side? I found some code that will do this for a specific folde... |
TL;DR
find "$dir" ! -type l -print0 |
sudo -u "$user" perl -Mfiletest=access -l -0ne 'print if -r'
You need to ask the system if the user has read permission. The only reliable way is to switch the effective uid, effective gid and supplementation gids to that of the user and use the access(R_OK) system call (even t... | How to recursively check if a specfic user has read access to a folder and its contents? |
1,489,601,181,000 |
I have a directory "Movies" containing subdirectories "Movie Name". Each subdirectory "Movie Name" contains a movie file and related image/nfo files etc.
I'm trying to copy all directories containing movie file of type ".avi" to an external usb device.
So if Directory/subdirectory A contains movie.avi, poster.jpg and... |
First, why your attempt doesn't work: -printf "%h\n" prints the directory part of the .avi file name. That doesn't affect anything in the subsequent -exec action — {} doesn't mean “whatever the last printf command printed”, it means “the path to the found file”.
If you want to use the directory part of the file name i... | Find and copy directories containing file type |
1,489,601,181,000 |
If I have input folder files_input that has subfilders like 01-2015, 02-2015, 03-2015 etc and all these subfolders have other subfolders. Each subfolder has only one file called index.html.
How can I copy all these index.html files into one folder called files_output so that they end up like separate files in the sam... |
As you're a zsh user:
$ tree files_input
files_input
|-- 01_2015
| |-- subfolder-1
| | `-- index.html
| |-- subfolder-2
| | `-- index.html
| |-- subfolder-3
| | `-- index.html
| |-- subfolder-4
| | `-- index.html
| `-- subfolder-5
| `-- index.html
|-- 02_2015
| |-- subfolder-1
| | ... | Recursive copy files with rename |
1,489,601,181,000 |
Say I have a folder:
/
/a.bub
/v.bub
/dr.bub
/catpictures
/catpictures/or.bub
/catpictures/on.bub
How can I format a script to change each of these to .aaa.
Here is what I've got, although it seems like a wrong approach:
find -type f -name "*.bub" -print0 -exec mv
|
You could use find and xargs:
$ find some_folder -type f -name "*.bub" |
sed "s/\.bub$//" |
xargs -I% mv -iv %.bub %.aaa
`some_folder/a.bub' -> `some_folder/a.aaa'
`some_folder/v.bub' -> `some_folder/v.aaa'
`some_folder/dr.bub' -> `some_folder/dr.aaa'
`some_folder/catpictures/or.bub' -> `some_folder/catpictu... | How can I rename all files with one extension to a different extension recursively [duplicate] |
1,489,601,181,000 |
I have got the directory called Test and a few directories inside it. Both Test and the directories inside it have executable files. I'd like to print them with ls. I'd use this command.
ls -l `find Test/ -perm /u=x,g=x,o=x -type f`
Is this a good/right/quick command or not?
My solution is:
find Test/ -executable -ty... |
Not really, you can integrate the ls command with find,
find Test/ -type f -perm /u=x,g=x,o=x -exec ls -l {} \;
UPDATE
Actually -executable is not an equivalent of -perm /u=x,g=x,o=x. You might have files that is executable only by the group or others, which will not be displayed.
So, depends on your purpose, if you w... | Find executable files recursively |
1,489,601,181,000 |
When I do 'ls -R' in a directory, I get something like
./dir1
dir2 file1.txt file2.txt
./dir1/dir2
file3.txt file4.txt
but I would like a command that gives me
./dir1/file1.txt
./dir1/file2.txt
./dir1/dir2/file3.txt
./dir1/dir2/file4.txt
such that I can use it in a for-loop to process all files.
|
You want find(1). This will do exactly what you want. You can also specify various filter conditions such as file type (don't include directories), newer than the time stamp on a given file etc. The man page will describe these in more detail.
Also, take a look at the -exec option; you may be able to use this inste... | recursive 'ls' giving absolute filenames |
1,489,601,181,000 |
I have many files in a specific repository and i must find a file which has a specific string in its content (actually referencing the file Version.cc.in). What is the best solution to find it?
|
You could use grep:
grep "text" /path/to/directory/*
For recusive search you could use -r option for grep:
grep -r "text" /path/to/directory/*
or ** in path:
grep "text" /path/to/directory/**/*
but, availability of ** operator is shell dependent - as far I know it is in zsh and bash (4 only?), it may not be availab... | Find file by a part of its content |
1,489,601,181,000 |
I am a moderately new linux user. I changed my PC, and started using CentOS 7 from CentOS 6.
So I attached my previous hard disk to my new pc to take backup of my files. Now, copying the files (and preserving the permissions and all), the files shows owner as 500 (I guess this is my previous UID).
Is there any way I ... |
If I understand you correctly, you want to change the owner of all files inside some directory (or the root) that are owned by user #500 to be owned by another user, without modifying files owned by any other user. You're in that situation because you've copied a whole directory tree from another machine, where files ... | Change file ownership, based on previous owner |
1,321,630,566,000 |
I'm using the Perl rename command line tool to search recursively through a directory to rename any directories as well as files it finds. The issue I'm running into is the rename command will rename a sub-directory of a file then attempt to rename the parent directory of the same file. This will fail because the sub-... |
I would go about this in a different way - specifically, using a depth-first search in place of the shell globstar **
For example, using GNU find, given:
$ tree
.
└── dir
├── foo
│ └── baz
│ └── MainFoo.c
└── Foo
├── baz
└── MainFoo.c
5 directories, 2 files
then
find . -depth ... | Using Perl rename to rename files and directories |
1,321,630,566,000 |
I am trying to print all directories and sub directories with a recursive function but I get only the first directory. Any help?
counter(){
list=`ls $1`
if [ -z "$(ls $1)" ]
then
exit 0
fi
echo $list
for file in $list
do
if [ -d $file ]
then
echo $file
... |
You can use something similar to this:
#!/bin/bash
counter(){
for file in "$1"/*
do
if [ -d "$file" ]
then
echo "$file"
counter "$file"
fi
done
}
counter "$1"
Run it as ./script.sh . to recursively print directories in under the current directory or give the path t... | Print recursively all directories and subdirectories |
1,321,630,566,000 |
Command I have is:
time find . -type f -print -exec cp {} /dev/null \;
This command finds all files in current folder and subfolders, print the name of each file and copy each of them to /dev/null. At the end it shows how much time it took to copy all the files.
What I need is to count (show) all copied bytes at the ... |
Not sure I understand your question fully, but what about:
find . -type f -exec pv -N {} {} \; > /dev/null
Gives an output like:
./file1: 575kB 0:00:00 [1.71GB/s] [=======================>] 100%
./file2: 15.2GB 0:00:07 [2.22GB/s] [==> ] 15% ETA 0:00:38
| Read all files in folder and subfolders - progress and size |
1,321,630,566,000 |
In AIX really, how can I search in several directories and those below it, for files that are not of the specific permissions of 755.
So I want to search /path/to/, /path/to/mydir, /path/to/mydir/andthisoneto, etc., but not /path.
|
If I understand correctly, you want this:
find /path -mindepth 2 -type f -not -perm 0755
Or maybe just this, if my understanding is off:
find /path/to -type f -not -perm 0755
| Search for file permisions other than 755 |
1,321,630,566,000 |
I need to set the same permissions of owner to group recursively to all elements in a directory.
|
There's a fairly simple answer
(although I don't know for sure whether it works on all versions of *nix);
simply do
chmod g=u *
i.e., set the group permissions equal to the user permissions.
This is documented in chmod(1):
The format of a symbolic mode is [ugoa...][[+-=][perms...]...],
where perms is either zero o... | Set group permissions as owner permissions |
1,321,630,566,000 |
I have a fairly large directory that I need to sync to an external hard drive for both backup and portability reasons.
/work
I try to run the following rsync command in order to copy this folder to my external hard drive:
rsync -avz /work /media/extern_drive --max-size '4G'
Which seems to work fine, EXCEPT that it d... |
I surmise that your external drive uses a filesystem such as VFAT which doesn't allow colons in file names.
A simple option would be to back up your files as archives (zip, 7z, tar.xz, whatever catches your fancy). This way you wouldn't be limited by any characteristic of the filesystem other than the maximum file siz... | rsync with colons in filenames |
1,321,630,566,000 |
I have 40 files in a directory and I want to count the number of times there is a line with a "2" in the first column in each file individually.
I am trying something like this, but it prints out the total sum from each file and I want the individual sums:
find . -type f -print0 | xargs -0 awk '($1=="2"){++count} END... |
You can have grep count them for you.
Assuming the lines you need start with 2, you can use the following:
grep -c '^[[:space:]]*2\>' $(find . -type f -print0 | xargs -0 echo)
The \> at the end of the regex ensures matching will stop at a "word boundary" to avoid false alarms such as lines starting with 20 instead of... | Count number of lines with a certain value in a column for all files in directory recursively |
1,321,630,566,000 |
I am trying to implement a makefile for my C project which has a directory structure as follows:
PROJECT_FOLDER:
folder1
folder2
folder // n number of folders
main.c
FOLDER1:
subfolder1
subfolder // n number of subfolders
And subfolder 1 can have further subfolders etc.. etc..
I don't intend ... |
You have the wildcard in the dirs pattern backward.
You wanted:
dirs = * parse/* parse/test/*
As written, your pattern above expanded to: *.c (good), */parse.c (lucky!), and */parse/test.c, which would have confused you even more if that file existed.
The only reason it looked like it worked for the first level direc... | Makefile $wildcard only matches top directory |
1,321,630,566,000 |
I have a directory which contains files and sub directories, some of which have whitespace in their names. Further more each of these sub directories contains files with whitespace in their names. Is there a simple way to remove the whitespace from all the names in the parent directory and all sub directories at once?... |
Is there a simple way to remove the whitespace from all the names in the parent directory and all sub directories at once?
Yes there is:
find /tmp/ -depth -name "* *" -execdir rename 's/ /_/g' "{}" \;
Further Reading
Good Luck!
| remove whitespace from all items in a directory and sub directory |
1,321,630,566,000 |
I am trying to make a script that will list all files and directories in a given directory. I want to make this script to call itself, in the end showing all files and directories. I know that you can easily do that with find, but I want to practice recursive scripts, and I don't know why my recursive given parameter ... |
The following line is the culprit:
. Script.sh $source
While you could conceivably do recursion that way, it makes it hard to reason about because the variables changed by the next level of recursion are changed in the caller as well. Probably you just want to invoke it without sourcing it:
Script.sh $source
Or, bet... | Recursive call script |
1,321,630,566,000 |
I am using the zutils version of zgrep v0.9 (not the gzip wrapper script) and to recursively grep zip files starting from the current folder I simply use:
zgrep -r "MY_STRING" .
This works fine. However, it does not search zip files within zip files.
How do I grep recursively across a directory and recursively search... |
The zgrep utility from zutils doesn't support zip files at all. It treats them as ordinary files, so it won't find anything except in members that are stored in raw format (which mostly happens for very small files).
The zipgrep utility distributed with unzip doesn't search zip files recursively.
For how to solve your... | Will zgrep recursively search zips embedded within zips? |
1,321,630,566,000 |
I am trying to recursively convert all .mkv files in a folder structure with subfolders to .mp4.
I got a standard line that works in just the present folder
for video in *.mkv; do ffmpeg -i "$video" -acodec aac -ac 2 "${video%.*}".mp4; rm "$video"; done
So I thought I would make something like
for video in $(find . ... |
Your error lies in using find in a command substitution. A command substitution always results in a single string. If you leave the substitution unquoted, that string will undergo splitting on spaces, tabs and newlines (by default). The split-up words will be processed for filename globbing. The resulting strings are... | Handle names with spaces when iterating recursively over files [duplicate] |
1,321,630,566,000 |
I've made today the greatest error on my server using root user:
chown -R 33:33 /
instead of chown -R 33:33 . within some webroot folder.
Well, this brought ssh down. I made it this far to get it working again, so far apache, mysql and php are still working, but I don't know if I ever restart them, or if the server ... |
No, no chance. You have to reinstall the system.
There are lists in the internet, how to re-chown (or chmod) the filesystem, but you can never cover all files. Those are attempt to solve this without reinstalling. But, I'm sorry for the bad news; The only correct solution is reinstalling, even if you aborted the comma... | Recovering from a chown -R / [duplicate] |
1,321,630,566,000 |
I'm trying to move the following move a large number of files that exist in the following structure to a /mnt/originals but I need to maintain the structure at the same time. I know cp would be a solution but can't use cp because of space limitations.
/mnt/originals-us/4
/mnt/originals.us/4/0b9
/mnt/originals.us/4/0b... |
One option would be to use rsync with --remove-source-files
rsync -vr --remove-source-files /mnt/originals-us/ /mnt/originals/
Potential caveat: I do not know how rsync checks for space before performing potentially damaging actions. In a perfect world, rsync would calculate how much space is needed, check to see i... | Moving large numbers of files and directories to a different directory |
1,321,630,566,000 |
I have a script that renames, getting rid off the whitespace, every directory and file. It does it recursively:
#!/bin/bash
find -name "* *" -print0 | sort -rz | \
while read -d $'\0' f; do mv -v "$f" "$(dirname "$f")/$(basename "${f// /_}")"; done
When I ran it in my ~ directory, the script wrought some unintende... |
Just use zsh's zmv:
#! /bin/zsh -
autoload -Uz zmv
zmv '(**/)(* *)' '$1${2// /_}'
zmv skips hidden files and files in hidden dirs by default (unless you pass a (#qD) qualifier to the first argument),
it processes the files depth first (your sort -rz is not guaranteed to work for that and -prune is not compatible wit... | How might one except hidden '.' files and directories from a script that renames them? |
1,321,630,566,000 |
I would like to view the unique owners of all the files and directories underneath a certain directory.
I have tried:
ls -ltR <dir-path> | grep -P '^[d|\-]' | awk '{print $3}' | sort | uniq
Which commits the cardinal sin of trying to parse ls output, but works -- until I try it on a directory with an immense amount o... |
Here's a slightly shorter version that uses find:
find <path> -printf "%u\n" | sort -u
Depending on the complexity of the directory structure, this may or may not be more efficient.
| Efficient search of unique owners of files and directories |
1,321,630,566,000 |
What a long title. Essentially, what I have is a collection of files that need to be searched recursively with a regex, and replaced.
What I have so far works without capture groups, however it does nothing when using them. I am currently using a command that I found on another question:
grep -rlP "/\* *(\d+) *\*/ (.... |
Replace -P with -E in grep and use [[:digit:]] or [0-9]+ instead of (\d+) since you don't use any other Perl-compatible things and you don't need the parentheses
Remove (.*) from grep, this is redundant
Add -E to sed or you have to escape your capturing groups (...) and the +
Sed doesn't understand \d+, replace it wi... | Recursively replace with RegEx w/ grep & sed while maintaining capture groups? |
1,321,630,566,000 |
I have a backup from a disk that contains data files and analysis. The dir structure and names are not really consistent. To save space, I would like to zip all the subdirs that only contain data (*.txt) and delete the original afterwards. There are several threads on zipping subdirs, but not on the conditions I have.... |
This script will archive then optionally remove all folders containing "*.txt" files and nothing else.
folders=$(find . -type d -exec sh -c 'cd "$1";[ "$(ls *.txt 2>/dev/null)" ] \
&& [ -z "$(ls -ad * | grep -v '\.txt$')" ] && echo "$1"' sh {} \;)
echo "$folders" | zip -r@ archive && echo "$folders" | while... | How to zip recursively all subdirectories that only contain text files |
1,321,630,566,000 |
I have constructed an elaborate 500+ character command with many arguments and switches to autosign multiple PDF documents.
I'm using JSignPDF and I'd like to use it's batch mode including the current directory and subdirectories.
The relevant part of the command I'm having trouble with is:
java -jar ../jsignpdf-1.4.3... |
With zsh or ksh93 -G, you could do:
java -jar ../jsignpdf-1.4.3/JSignPdf.jar ./**/*.pdf -a
You could do the same with fish or bash -O globstar, but beware that those may traverse symlinks when descending the directory tree (fixed partly in bash 4.3, fully in 5.0 and above).
Otherwise, if the list of files is not too ... | Passing all files of specific filetype in current and subdirectories |
1,321,630,566,000 |
On a mac I'm migrating a create react app to vite and have a lot of *.js files that need changing to *.jsx. I done this manually once in my life and this is enough for one eternity.
I need a simple to understand script to do this preferably on a mac installation without needing to install anything.
I'v found lots of e... |
Try this.
$ find . -name '*.js' -exec echo mv {} {}x \;
mv ./a/a.js ./a/a.jsx
mv ./a/z/z.js ./a/z/z.jsx
mv ./b/b.js ./b/b.jsx
$
Once you're happy with how the proposed commands look, just remove the echo part, and give it a spin.
If you have directories named .js, this won't work and will need -type f adding.
Bonus P... | BASH recursive rename of js files to jsx |
1,321,630,566,000 |
I want to use grep where paths are arbitrary depth under the directory /path/to/dir and has the file name foo. I thought that the wildcard for arbitrary depth is **, and I tried
grep some_pattern /path/to/dir/**/foo
but it seems to be matching only files where the ** part represents a single directory depth like
/pat... |
Use zsh. In the zshexpn(1) man page, Section "Recursive Globbing":
A pathname component of the form '(foo/)#' matches a path consisting of
zero or more directories matching the pattern foo.
As a shorthand, '**/' is equivalent to '(*/)#'; note that this therefore
matches files in the current directory as well as s... | Wildcard for arbitrary depth |
1,321,630,566,000 |
My problem is that I need to:
Find all lines matching regex_pattern in all files (deep search) in a given root directory
For each line that matches, output:
File name
Line number containing the match
Line contents
The regex pattern
Import the above data into Excel (so a CSV, or delimited output format comes to mind... |
Something like this?
find /search/root -type f -exec awk 'BEGIN{pattern="regex_pattern"} $0 ~ pattern {printf "%s,%s,%s,%s\n",FILENAME,FNR,$0,pattern}' {} +
| Help searching in files for regex patterns, recursively, with specialized output |
1,321,630,566,000 |
This question follows from: How do I create a local copy of a complete website section from OSX using curl?
After discovering OSX's native curl wouldn't do this task I downloaded wget from here: http://www.techtach.org/wget-prebuilt-binary-for-mac-osx-lion
But performing:
./wget -r -l 0 https://ccrma.stanford.edu/~jos... |
try adding:
--no-parent
"Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded."
In my experience it also prevents downloading from other sites.
| How do I create a local copy of a complete website section from OSX using wget? |
1,321,630,566,000 |
Based on this answer, I want to perform an operation on all the files in a directory and its subdirectories.
The following command works a single file, and also works when used on multiple files in a loop.
for i in *.html; \
do sed -i '/<head>/a <link rel="stylesheet" href="/home/jian/postgres/doc/src/sgml/html/styles... |
Calling sed from find for all regular files with names matching *.html in the current directory or below:
find . -name '*.html' -type f -exec sed -i '...expression...' {} +
Assuming you correctly insert your sed expression in the code above, this will call sed with batches pathnames of found files, ensuring that sed ... | Recursively perform an operation on all files in a directory and its subdirectories |
1,321,630,566,000 |
Basically, my hard drive is a mess and I have like 200+ sub-directories in a main directory. I want to essentially move all files in 200+ sub-directories that have the extension .txt etc to a new directory. For example, n00b.txt or n00b.txt.exe
So I try the following command in the main directory consisting of the 200... |
This would move all files with .txt and .txt.exe extensions present anywhere inside the current directory (even in subdirectories) to ~/Desktop/tmpremo.
$ sudo find . -type f \( -iname '*.txt' -o -iname '*.txt.exe' \) -exec mv {} ~/Desktop/tmpremo \;
If you want another extension too, just add -o -iname '*.extension'... | Moving all files with same file extension .txt to a new directory |
1,321,630,566,000 |
I'd like to apply chmods to files and folders in one line,
Basically:
chmod 700 ./* -R # but only apply to folders
chmod 600 ./* -R # but only apply to files
Of course I searched google and read manpages.
So the question is, does the following have any drawbacks, risks or is this safe?
find . -type f -print0 | xargs ... |
There is another possibility which I discovered using ACLs: the uppercase X. Given the following structure (three directories, three files):
drw------- 1/
drw------- 2/
drw------- 3/
-rw------- 4
-rw------- 5
-rw------- 6
It is possible to set the execution but for directories only by using:
chmod u+X *
Which will r... | Apply recursive chmod to files or folders only |
1,321,630,566,000 |
I have a large archive of edited images from my camera, each image is actually a pair of files - *.nef & *.xmp. I would like to go through all the folders and then zip these pairs into single tgz files.
Each of the filenames in a directory is unique, so it would be sufficient to move the file names from output of ls *... |
A short script, xfun:
#!/bin/bash
b=$(basename "$1" .xmp)
# echo "tar -cjf $b.tar.bz2 $b.xmp $b.nef"
tar -cjf "$b.tar.bz2" -- "$b.xmp" "$b.nef"
Invocation:
find -name "*xmp" -execdir ./xfun {} ";"
| Find files with same name but different extensions, send to tgz |
1,321,630,566,000 |
So I'm asking myself why there is the "-R" argument for the "tree" command.
The manual says "-R Recursively cross down the tree each level directories ...", but I don't see any difference in the result between those two.
|
The -R option is only effective in HTML output mode, and is ignored if you don’t also specify a maximum display depth with the -L option.
tree -R -L 2 -H . -o tree.html
will output the tree to tree.html, and additionally generate subtrees every two levels in OOTree.thml files in each corresponding directory.
| Command "tree" vs "tree -R" |
1,321,630,566,000 |
Given a nested directory structure containing various files, I would like to find all the files within it, but where there are multiple files with the same name, I'd like to return just the largest file.
So, for example, given a directory structure like:
|--- foo.jpg (110 KB)
|--- bar.jpg (210 KB)
|--- dir
|----... |
With zsh:
typeset -A files
for f (**/*(D.oL)) files[$f:t]=$f
printf '%s\n' $files
Would work whatever bytes or characters (like space, newline...) the file names may contain.
With GNU tools:
find . -type f -printf '%s/%f/%P\0' |
sort -zrn |
LC_ALL=C sort -zt/ -uk2,2 |
tr '\0\n' '\n\0' |
cut -d/ -f3- |
tr '\... | Find files recursively, but choose largest from among those with duplicate names |
1,321,630,566,000 |
how can we copy only file details (filename, size, time) from a remote machine in Unix?
For example: I have a directory (/opt/apache/…/webapps/Context) placed on a remote machine. Now I want to copy only the metadata (size, time, filename) of the files that reside in this directory and its subdirectories to my local m... |
If you want to get a detailed listing of the files in directory opt/apache../webapps/Context on remote machine remotemachine, use:
ssh remotemachine "ls -l /opt/apache../webapps/Context"
If you want to search recursively for all files in that directory and all its subdirectories, then use:
ssh remotemachine "find /... | Copy only file details (file name, size, time) from remote machine in unix |
1,321,630,566,000 |
I would like to set an environment variable (that we'll call "TEST") to store the path to a sub-directory of my home directory : something like /home/myself/dir/. I would like to use the $HOME variable so that the system can get a path that is valid for any user on the system (provided they have a directory called "d... |
You can do this, but it requires at least 2 shell variable evaluations, and, normally, all you ever get is one. This is by design - I mean, the shell is where all of your stuff is, so it's best to limit the unexpected to a minimum and avoid opening doors behind doors if you can help it. In any case, you definitely hav... | setting environment variable as a function of another env variable [duplicate] |
1,321,630,566,000 |
I'm trying to write a zsh script on MacOS Big Sur that will recursively rename some files and directories that have special characters I don't want. Been at it for days and every time I think I have it cracked, I get hit with a new problem. It's basically done, except that when I run the find command in dry run mode:
... |
Since you're using Zsh, I would just use zmv for this instead of find:
% autoload -Uz zmv
% zmv -n '(**/)(*)(#q.)' '$1${2//[^. [:IDENT:]]/-}' # -n: no execute
mv -- 'untitled file2 [].txt' 'untitled file2 --.txt'
mv -- 'untitled file3 [].txt' 'untitled file3 --.txt'
% zmv -v '(**/)(*)(#q.)' '$1${2//[^. [:IDENT:]]/-}'... | zsh find -execdir rename "no such file or directory" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.