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 results. What am I doing wrong?
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 that it must ignore other filesystems - this is good for avoiding special filesystems such as /proc. However it will also ignore normal filesystems too - so if, for example, your /home folder is on a different partition, it won't be searched - you would need to say find / /home -xdev .... -type f means search for files only, so directories, devices and other special files are ignored (it will still recurse into directories and execute grep on the files within - it just won't execute grep on the directory itself, which wouldn't work anyway). And the -H option to grep tells it to always print the filename in its output. find accepts all sorts of options to filter the list of files. For example, -name '*.txt' processes only files ending in .txt. -size -2M means files that are smaller than 2 megabytes. -mtime -5 means files modified in the last five days. Join these together with -a for and and -o for or, and use '(' parentheses ')' to group expressions (in quotes to prevent the shell from interpreting them). So for example: find / -xdev '(' -type f -a -name '*.txt' -a -size -2M -a -mtime -5 ')' -print0 | xargs -0 grep -H "800x600" Take a look at man find to see the full list of possible filters.
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 the largest file. EX: dude@shell2 (~...assignment/solutions) % bash maxfile.sh ~/test class/asn dude.h.gch: 9481628 This is what I have: #!/bin/sh clear recursiveS() { for d in *; do if [ -d $d ]; then (cd $d; echo $(pwd)/$line; du -a; recursiveS;) fi done } recursiveS I have been stuck for a while now. I cannot implement this by pipelining a number of existing Unix tools. Any ideas would be nice!
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 **; do if [[ -f "$f" && ! -L "$f" ]]; then size=$( stat -c %s -- "$f" ) if (( size > max_s )); then max_s=$size max_f=$f fi fi done echo "$max_s $max_f" This will be significantly slower than the find solution. That also assumes that file names don't end in newline characters and will skip hidden files and not descend into hidden directories. If there's a file called - in the current directory, the size of the file open on stdin will be considered. Beware that versions of bash prior to 4.3 followed symbolic links when descending the directory tree.
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 example: find ./logs -size +1c > t._tmp while read filename do grep -q "Process Complete" $filename if [ $? -ne 0 ] ; then echo $filename fi done < t._tmp rm -f t_tmp But that's cumbersome and not at all concise. ps: I know that grep -L * will do this, but how can I use the find command in combination with grep to excluded files is what I really want to know. pss: Also I'm not sure how to have grep include subdirectories with the grep -L * syntax, but I still want to know how to use it with find :)
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 the output.
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 \! -newer stop
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 write a different command. find: `./3/obj': No such file or directory find: `./3/build': No such file or directory find: `./1/obj': No such file or directory find: `./1/build': No such file or directory find: `./2/obj': No such file or directory find: `./2/build': No such file or directory
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 current directory. The equivalent of your GNU -regex-type one would be: find . \( -name build -o -name obj -o -name '*?.so' \) -prune -exec rm -rf {} + Note that if you're going to use GNU specific syntax, you might as well use -delete instead of -exec rm -rf {} +. With -delete, GNU find turns on -depth automatically. It doesn't run external commands so in that way, it's more efficient, and also it's safer as it removes the race condition where someone may be able to make you remove the wrong files by changing a directory to a symlink in-between the time find finds a file and rm removes it (see info -f find -n 'Security Considerations for find' for details). find . -regextype posix-egrep -regex '.*/((obj|build)(/.*)?|.+\.so)' -delete
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 logic behind the selection of case for these arguments?
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 -L/-H/P options to give the user a chance to decide what to do with symlinks leaving the default when none is provided unspecified. POSIX grep has no -r or -R. GNU grep initially had neither. -r was added in 1998. That was following symlinks. -R was added as a synonym in 2001 for consistency with the other utilities. That was still following symlinks. In 2012 (grep 2.12), -r was changed so it no longer followed symlinks, possibly because -L, -H were already used for something else. BSDs grep were based on GNU grep for a long time. Some of them have rewritten their own and kept more or less compatibility with GNU grep. Apple OS/X addressed the symlink issue differently. -r and -R are the same and don't follow symlinks. There's a -S option however that acts like chmod/cp/find's -L option to follow symlinks.
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 problematic: you can't use -exec in the inner find, because the terminator would be seen as a terminator by the outer find. You can work around that by invoking a shell, but beware of quoting. find . -name my-search-term -prune -exec sh -c ' find "$@" … -exec … {\} + ' _ {} +
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. First, the normal case: $ mkdir src src/src_dir dest && touch src/src_file src/.dotfile dest/dest_file $ cp -r src dest $ ls -A dest dest_file src Then, with /. at the end: $ mkdir src src/src_dir dest && touch src/src_file src/.dotfile dest/dest_file $ cp -r src/. dest $ ls -A dest dest_file .dotfile src_dir src_file So, this behaves simlarly to *, but also copies hidden files. $ mkdir src src/src_dir dest && touch src/src_file src/.dotfile dest/dest_file $ cp -r src/* dest $ ls -A dest dest_file src_dir src_file . and .. are proper hard-links as explained here, just like the directory entry itself. Where does this behaviour come from, and where is it documented?
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 the parent directory. Neither are special as far as the shell is concerned, so neither are concerned by expansion, and the directory will be copied including hidden files. *, on the other hand, will be expanded to a list of files, and this is where hidden files are filtered out. src/. is the current directory inside src, which is src itself; src/src_dir/.. is src_dir’s parent directory, which is again src. So from outside src, if src is a directory, specifying src/. or src/src_dir/.. as the source file for cp are equivalent, and copy the contents of src, including hidden files. The point of specifying src/. is that it will fail if src is not a directory (or symbolic link to a directory), whereas src wouldn’t. It will also copy the contents of src only, without copying src itself; this matches the documentation too: If target exists and names an existing directory, the name of the corresponding destination path for each file in the file hierarchy shall be the concatenation of target, a single slash character if target did not end in a slash, and the pathname of the file relative to the directory containing source_file. So cp -R src/. dest copies the contents of src to dest/. (the source file is . in src), whereas cp -R src dest copies the contents of src to dest/src (the source file is src). Another way to think of this is to compare copying src/src_dir and src/., rather than comparing src/. and src. . behaves just like src_dir in the former case.
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 -l 0 http://www.omardo.com/blog (my own blog)
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 proxy should do is: Take HTTP requests from Scrapy and sends it to the server being crawled. Then it gives back the response from to Scrapy i.e. intercept all HTTP traffic. For binary files (based on a heuristic you implement) it sends 403 Forbidden error to Scrapy and immediate closes the request/response. This helps to save time, traffic and Scrapy won't crash. Sample Proxy Code That actually works! http.createServer(function(clientReq, clientRes) { var options = { host: clientReq.headers['host'], port: 80, path: clientReq.url, method: clientReq.method, headers: clientReq.headers }; var fullUrl = clientReq.headers['host'] + clientReq.url; var proxyReq = http.request(options, function(proxyRes) { var contentType = proxyRes.headers['content-type'] || ''; if (!contentType.startsWith('text/')) { proxyRes.destroy(); var httpForbidden = 403; clientRes.writeHead(httpForbidden); clientRes.write('Binary download is disabled.'); clientRes.end(); } clientRes.writeHead(proxyRes.statusCode, proxyRes.headers); proxyRes.pipe(clientRes); }); proxyReq.on('error', function(e) { console.log('problem with clientReq: ' + e.message); }); proxyReq.end(); }).listen(8080);
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 drwxrwxr-x 2 4096 Jul 9 10:29 dir3 -rw-rw-r-- 1 0 Jul 9 10:29 file1 -rw-rw-r-- 1 0 Jul 9 10:29 file2 lrwxrwxrwx 1 5 Jul 9 10:29 link1 -> link1 lrwxrwxrwx 1 5 Jul 9 10:30 link2 -> link2 What I would like to get ~/test$ ls -somthing (or bash hack) total 12 dir1 dir2 dir3 file1 file2 NOTE: My main motivation is to do a recursive grep (GNU grep 2.10) without following symlinks.
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 !, which means negate the following test. In combination they match every file that is not a symlink. This lists all files and directories recursively, but no symlinks. If you just want regular files (and not directories): find . -type f To include only the direct children of this directory, and not all others recursively: find . -mindepth 1 -maxdepth 1 You can combine those (and other) tests together to get the list of files you want. To execute a particular grep on every file matching the tests you're using, use -exec: find . -type f -exec grep -H 'some pattern' '{}' + The '{}' will be replaced with the files. The + is necessary to tell find your command is done. The option -H forces grep to display a file name even if it happens to run with a single matching file.
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) However, it seems like this doesn't work for files containing obscure characters: $ touch $'a\nb' $ find . -type f ./a?b Is there an alternative that handles such obscure characters well?
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 faster.) This makes it possible to use standard input within the loop, and it works with any path.
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 access you might want to run configure --prefix=/usr/local Such that the utilities install into /usr/local If you do not have root access you might want to run configure --prefix=${HOME} Such that the utilities install into your home directory
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 │   │   └── file │   └── file ├── 2 │   ├── A │   │   └── file │   └── file ├── 3 │   ├── A │   │   └── file │   ├── B │   │   ├── file │   │   └── I │   │   └── file │   └── file └── file 9 directories, 10 files
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 encountered. The string `{}' is replaced by the current file So, the command above will find all directories and run cp file DIR_NAME/ on each of them.
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 JS file in my directory structure?
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 and they don't change. My question is... when I call chmod 775 . -R does it try to set the permission for the files that already have the right permissions set, or only for the new files that don't have the right permissions? It seems to always take ages to get past this command in the script, even though the 'new' files are only a few thousand and it should do their permissions fairly quickly. I've looked at the man page for chmod, but it doesn't seem to mention anything on this case. If chmod doesn't check for permissions beforehand, should I start looking at combining 'find' with 'chmod'?
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 stating every file. You can try using find to either check for files newer than the last run or files that need chmod to be run, but I don't think you'll get much speed improvement. If possible for your script, you might be able to get the new files put into a separate directory first, as a "holding" area. Then you can chmod THAT directory (which only has new files), and mv them in with the rest. That should be substantially faster, but unfortunately won't work for every application. [0] Even if it does try to set the permission of files that don't need any changes, the underlying filesystem probably won't do anything with the request, because it's unnecessary.
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-able(even by the same dir name if I chose to recreate it) ?? So for e.g. not knowing much about zfs file system internals, specifically how it journals its files, I wonder if I was able to access that journal/map directly, for e.g., then remove the right entries, so that the dir would no longer display. That space dir holds has to be removed from some kind of audit as well. Is there an easy way to do this? Even if on an ext3 fs, or is that already what the recursive remove command has to do in the first place, i.e. pilfer through and edit journals? I'm just hoping to do something of the likes of kill thisDir to where it simply removes some kind of ID, and poof the directory no longer shows up in ls -la. The data is still there on the drive obviously, but the space will now be reused(overwritten), because ZFS is just that cool? I mean I think zfs is really that cool, how can we do it? Ideally? rubbing hands together :-) My specific use case (besides my love for zfs) is management of a backup archive. The data is pushed to zfs via freefilesync (AWESOME PROG) on/from win boxes across SMB to the zfs pool. When removing rm -rf /nas/dataset/certainFolder through a putty term, it stalls, the term is obviously unusable for a long time now. I of course then have to open another terminal, to continue. Thats gets old, plus its no fun to monitor the rm -rf, it can take hours. Maybe I should set the command to just release the handle e.g. &, then print to std out, that might be nice. More realistically, recreate the data-set in a few seconds zfs destroy nas/dataset; zfs create -p -o compression=on nas/dataset after the thoughts from the response from @Gilles.
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 extra code. If you create a snapshot of your file system before removing the directory, the directory removal will be very fast because nothing will need to be explored/freed under it, all being still referenced by the snapshot. You can then destroy the snapshot in the background so the space will be gradually recovered. d=yourPoolName/BackupRootDir/hostNameYourPc/somesubdir zfs snapshot ${d}@quickdelete && { rm -rf /${d}/certainFolder zfs destroy ${d}@quickdelete & }
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 watched. Total of 39 watches. Finished establishing watches, now collecting statistics. total attrib close_write open create filename 8 2 2 2 2 /tmp/ The output only prints the statistics, but not the files I expected (as in here or here). I tried different types of access (via cat, mktemp, etc.), but it's the same thing. Did I miss something? It's because I'm on VPS and something has been restricted? OS: Debian 7.3 (inotify-tools) on VPS
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 change happens on /tmp, not /tmp/test-1. Additionally, since /tmp/test-1 wasn't there when inotifywatch started, there is no inotify watch placed on it. It means that any event which occurs on a file created after the watches have been placed will not be detected. You might understand it better if you see it yourself: $ inotifywatch -rv /tmp & Total of n watches. $ cat /sys/kernel/debug/tracing/trace | grep inotifywatch | wc -l n If you have enabled the tracing mechanism on inotify_add_watch(2), the last command will give you the number of watches set up by inotifywatch. This number should the same as the one given by inotifywatch itself. Now, create a file inside /tmp and check again: $ inotifywatch -rv /tmp & Total of n watches. $ touch /tmp/test1.txt $ cat /sys/kernel/debug/tracing/trace | grep inotifywatch | wc -l n The number won't have increased, which means the new file isn't watched. Note that the behaviour is different if you create a directory instead : $ inotifywatch -rv /tmp & Total of n watches. $ mkdir /tmp/test1 $ cat /sys/kernel/debug/tracing/trace | grep inotifywatch | wc -l n + 1 This is due to the way the -r switch behaves: -r, --recursive: [...] If new directories are created within watched directories they will automatically be watched. Edit: I got a little confused between your two examples, but in the first case, the watches are correctly placed because the user calls inotifywatch on ~/* (which is expanded, see don_crissti's comment here). The home directory is also watched because ~/.* contains ~/.. Theoretically, it should also contain ~/.., which, combined with the -r switch, should result in watching the whole system. However, it is possible to get the name of the file triggering a create event in a watched directory, yet I'm guessing inotifywatch does not retrieve this information (it is saved a little deeper than the directory name). inotify-tools provides another tool, called inotifywait, which can behave pretty much like inotify-watch, and provides more output options (including %f, which is what you're looking for here) : inotifywait -m --format "%e %f" /tmp From the man page: --format <fmt> Output in a user-specified format, using printf-like syntax. [...] The following conversions are supported: %f: when an event occurs within a directory, this will be replaced with the name of the file which caused the event to occur. %e: replaced with the Event(s) which occurred, comma-separated. Besides, the -m option (monitor) will keep inotifywait running after the first event, which will reproduce a behaviour quite similar to inotifywatch's.
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 use to find the string only in .cs files?
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 supports --include, you can do a recursive grep and tell grep to only consider files matching certain patterns. Note the quotes around the file name pattern: it's interpreted by grep, not by the shell. grep -rn --include='*.cs' GetTypes . With only portable tools (some systems don't have grep -r at all), use find for the directory traversal part, and grep for the text search part. find . -name '*.cs' -exec grep -n GetTypes {} +
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/A-Z/a-z/' * It's from man rename.
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 range a through z, i.e. ASCII uppercase letters to the corresponding lowercase letter. To perform the opposite translation, use y/a-z/A-Z/. Another way to write the same command is rename '$_ = uc($_)' * — uc is the uppercase function, and the rename command renames files based on the transformation made to the $_ variable. rename '…' * only renames files in the current directory, because that's what * matches. Dot files (files whose name begins with .) are skipped, too. If you want to rename files in the current directory and in subdirectories recursively, you can use the find command to traverse the current directory recursively. There is a difficulty here: if you call rename, this renames both the directory and the base name part. If you call rename on a directory before recursing into it (find -exec rename … {} \;), find gets confused because it's found a directory but that directory no longer exists by the time it tries to descend into it. You can work around this by telling find to traverse a directory before acting on it, but then you end up attempting to rename foo/bar to FOO/BAR but the directory FOO doesn't exist. A simple way to avoid this difficulty is to make the renaming command act only on the base name part of the path. The regular expression ([^/]*\Z) matches the final part of the path that doesn't contain a /. find . -depth -exec rename 's!([^/]*\Z)!uc($1)!e' {} + The shell zsh provides more convenient features for renaming — even more cryptic than Perl, but terser and often easier to compose. The function zmv renames files based on patterns. Run autoload -U zmv once to activate it (put this line in your .zshrc). In the first argument to zmv (the pattern to replace), you can use zsh's powerful wildcard patterns. In the second argument to zmv (the replacement text), you can use its parameter expansion features, including history modifiers. zmv -w '**/*' '$1$2:u' Explanation: -w — automatic assign numeric variables to each wildcard pattern **/* — all files in subdirectories, recursively (**/ matches 0, 1 or more levels of subdirectories) $1 — the first numeric variable, here matching the directory part of each path $2:u — the second numeric variable, here matching the base name part of each path, with the :u modifier to convert the value to uppercase As an added bonus, this respects the ambient locale settings. If you aren't sure about a zmv command you wrote, you can pass the -n option to print what the command would do and not change anything. Check the output, and if it does what you want, re-run the command without -n to actually act.
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 word, so why doesn't recursion follow these upwards in the directory tree? Is there an artificial limit on rm app, or . and .. are not real things?
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 *.QTFS, any files recursively inside directories called *.QTFS, and those directories themselves. If you want that other deletion behaviour, use find -delete. current directory as displayed by ls -lha also contains . and .. links for the lack of a better word, so why doesn't recursion follow these upwards in the directory tree? Is there an artificial limit on rm app, or . and .. are not real things? It's an artificial limit of rm. It's not really all that artificial, though - it's the only way it could ever work. If rm followed the parent .. links, every rm -r would remove every file on the system, by following all of the .. links all the way back to /. rm sees the .. and . entries in each directory when it lists the content, and explicitly disregards them for that reason. You can try that out yourself, in fact. Run rm -r . and most rm implementations will refuse to act, reporting an error explicitly: $ rm -r . rm: refusing to remove ‘.’ or ‘..’ directory: skipping ‘.’ (that message is from GNU rm; others are similar). When it encounters these entries implicitly, rather than as explicit arguments, it just ignores them and continues on. That behaviour is required by POSIX. In GNU rm and many of the BSDs, it's provided automatically by the fts_read family of hierarchy-traversal functions. or . and .. are not real things? . and .. are generally real directory entries, although that is filesystem-specific. They will almost always be presented as though they are real entries to all user code, regardless. Many pieces of software (not just rm) special-case their behaviour in order to catch or prevent runaway or undesirable recursion.
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 wide/home directory even when I am on ~/Desktop. How can I implement so?
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 because it sounds dangerous, this is not a common extension for temporary files and there are plenty of non-temporary files with that name.) If your OS isn't Linux, replace -delete by -exec rm {} +. You should perhaps configure Vim to put its swap files in a single directory by setting the directory option: set dir=~/tmp/vim-swap-files//,/var/tmp// Create the directory first. The // at the end makes the swap file name include the directory location of the original file, so that files with the same name in different directories don't cause a crash. You can do the same thing for backup files with the backupdir option, though it makes a lot less sense. If you use Emacs, set auto-save-file-name-transforms to point every file to a single directory. (setq auto-save-file-name-transforms '("\\`.*\\'" "~/tmp/emacs-auto-save-files/\\&" t))
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 sub-directories?). However, my question is different: is there any single, built-in command that works through this magic, without having to write my shell script?
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/subsubdir1/song.mp3 dir/subdir2 dir/subdir2/subsubdir1 dir/subdir2/subsubdir1/document.pdf dir/subdir2/subsubdir1/another-song.mp3 dir/subdir2/subsubdir1/top-ten-movies.txt dir/subdir3 dir/subdir3/another-document.pdf After running the command, I'd like to have dir.tar.gz contain this: dir dir/subdir2 dir/subdir2/subsubdir1 dir/subdir2/subsubdir1/document.pdf dir/subdir3 dir/subdir3/another-document.pdf Possible?
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 empty directories)
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" directory itself (including everything within) to the "root" location where I unzipped (i.e. where "x" is, but not inside "x"). Assumptions: There exists a folder named "run", but I do not know how many directories I will have to "cd" to get to it (could be 3 (x,y,z), could be 10 or more. The names are also unknown and do not have to be x,y,z etc). How can I accomplish this? I tried many variations of this question but they all failed.
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 want wildcards to be expanded by a program other than the shell (e.g. by find, tar, scp, etc.) you need to quote them so the shell won't try to expand them itself.
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 that? I used cp --recursive folder0address targetfolderaddress But subfolders copied to target folder. I just want all files in directory and sub directories not folders. I mean something like the below in target folder: targetfolder file011 file012 file021 file01 file02
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 like the following (I've left off the audio conversion command and am instead using echo for illustration): $ find ./ -name '*.wma' -type f -print0 | xargs -0 -I f echo ${f%.*}.mp3 As I understand it, the -print0 arg will let me handle filenames that have spaces (which many of these do as they are music files). I'm then expecting (as a result of xargs) that each file path from find is captured in f, and that using the substring match/delete from the end of the string, that I should be echoing the original file path with a mp3 extension instead of wma. However, instead of this result, I'm seeing the following: *.mp3 *.mp3 *.mp3 *.mp3 *.mp3 *.mp3 *.mp3 *.mp3 *.mp3 ... So my question (aside from the specific 'what am I doing wrong here'), is this - do values that are the result of a pipe operation need to be treated differently in string manipulation operations than those that are the result of a variable assignment?
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 command, so if you'd used e.g. xargs -I e echo … it would have executed commands like ./somedir/somefile.wmacho .mp3). Keeping on this approach, tell xargs to invoke a shell that can perform the expansion. Better, tell find — xargs is a largely obsolete tool and is hard to use correctly, as modern versions of find have a construct that does the same job (and more) with fewer plumbing difficulties. Instead of find … -print0 | xargs -0 command …, run find … -exec command … {} +. find . -name '*.wma' -type f -exec sh -c 'for f; do echo "${f%.*}.mp3"; done' _ {} + The argument _ is $0 in the shell; the file names are passed as the positional arguments which for f; do … loops over. A simpler version of this command executes a separate shell for each file, which is equivalent but slightly slower: find . -name '*.wma' -type f -exec sh -c 'echo "${0%.*}.mp3"' {} \; You don't actually need to use find here, assuming you're running a reasonably recent shell (ksh93, bash ≥4.0, or zsh). In bash, put shopt -s globstar in your .bashrc to activate the **/ glob pattern to recurse in subdirectories (in ksh, that's set -o globstar). Then you can run for f in **/*.wma; do echo "${f%.*}.mp3" done (If you have directories called *.wma, add [ -f "$f" ] || continue at the beginning of the loop.)
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 paths. #!/bin/bash # Choose which script to use for the final awk step out_script=out_all # Print all duplicated file names, even when md5sum is the same out_all='{ if( p1 != $1 ) { print nl $1; print I $2 } else if( p2 != $2 ) { print I $2 } print I I $3; p1=$1; p2=$2; nl="\n" } END { printf nl}' # Print only duplicated file names which have multiple md5sums. out_only='{ if( p1 != $1 ) { if( multi ) { print pend } multi=0; pend=$1 "\n" I $2 "\n" } else if( p2 != $2 ) { multi++; pend=pend I $2 "\n" } pend=pend I I $3 "\n"; p1=$1; p2=$2 } END { if( multi ) print pend }' # The main pipeline find "${1:-.}" -type f -name '*' | # awk for duplicate names awk -F/ '{ if( name[$NF] ) { dname[$NF]++ } name[$NF]=name[$NF] $0 "\n" } END { for( d in dname ) { printf name[d] } }' | # standard md5sum output xargs -d'\n' md5sum | # " "==text, "*"==binary sed 's/ [ *]/\x00/' | # prefix with file name awk -F/ '{ print $3 "\x00" $0 }' | # sort by name. md5sum, path sort | # awk to print result awk -F"\x00" -v"I= " "${!out_script}" Output showing only file names with multiple md5s afile.html 53232474d80cf50b606069a821374a0a ./test/afile.html ./test/dir.svn/afile.html 6b1b4b5b7aa12cdbcc72a16215990417 ./test/dir.svn/dir.show/afile.html Output showing all files with the same name. afile.html 53232474d80cf50b606069a821374a0a ./test/afile.html ./test/dir.svn/afile.html 6b1b4b5b7aa12cdbcc72a16215990417 ./test/dir.svn/dir.show/afile.html fi le.html 53232474d80cf50b606069a821374a0a ./test/dir.svn/dir.show/fi le.html ./test/dir.svn/dir.svn/fi le.html file.html 53232474d80cf50b606069a821374a0a ./test/dir.show/dir.show/file.html ./test/dir.show/dir.svn/file.html file.svn 53232474d80cf50b606069a821374a0a ./test/dir.show/dir.show/file.svn ./test/dir.show/dir.svn/file.svn ./test/dir.svn/dir.show/file.svn ./test/dir.svn/dir.svn/file.svn file.txt 53232474d80cf50b606069a821374a0a ./test/dir.show/dir.show/file.txt ./test/dir.show/dir.svn/file.txt ./test/dir.svn/dir.show/file.txt ./test/dir.svn/dir.svn/file.txt
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 operations in one command for all workspace directories? I can run the following command: chmod -R 774 * But this also changes the mode of parent directories, which is not desired.
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 a duplicate, I've trawled through examples and can't find an answer to this. Thanks
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 print the list of subdirectories of the current directory recursively: find -type d print -l **/*/ This is actually an svn checkout: $ find -type d ./.deps ./.svn ./.svn/text-base ./.svn/prop-base ./.svn/tmp ./.svn/tmp/text-base ./.svn/tmp/prop-base ./.svn/tmp/props ./.svn/props ./lib/.svn ./lib/.svn/text-base ./lib/.svn/prop-base ./lib/.svn/tmp ./lib/.svn/tmp/text-base ./lib/.svn/tmp/prop-base ./lib/.svn/tmp/props ./src/.svn ./src/.svn/text-base ./src/.svn/prop-base ./src/.svn/tmp ./src/.svn/tmp/text-base ./src/.svn/tmp/prop-base ./src/.svn/tmp/props I want to exclude the .svn directories and their subdirectories which are present in every directory. It's easy with find: find -type d -name .svn -prune -o -print Can I do this with a short zsh glob? Ignoring dot files comes close (I need to do it explicitly because I have glob_dots set): print -l **/*(/^D) But this isn't satisfactory because it hides the .deps directory, which I do want to see. I can filter out the paths containing .svn: print -l **/*~(*/|).svn(|/*)(/) But that's barely shorter than find (so what am I using zsh for?). I can shorten it to print -l **/*~*.svn*(/), but that also filters out directories called hello.svn. Furthermore, zsh traverses the .svn directories, which is a bit slow on NFS or Cygwin. Is there a convenient (as in easy to type) way to exclude a specific directory name (or even better: an arbitrary pattern) in a recursive glob?
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 command rm -rf *: The shell resolves the wildcard patterns (* in this case) to all files (including directories, symbolic links and device special files) that matches the used globbing pattern, in this case everything not beginning with a . Normally, these are sorted "alphabetically" by the shell. The shell then forks a new process and exec()s the first version of rm found in your $PATH, with -rf as the first argument, and the matched files, one by one as the consecutive arguments. If the rm that was invoked was the standard rm command, it first parses the arguments, one by one, treating all arguments (including ones resulting from shell globbing) that begin with a - as options until it comes to an argument that does not begin with a - (except for commands using GNU getopt() that accept options after non-options), or one that is exactly --. Everything after that is considered file names. In other words, if you had a file called (for example) --no-preserve-root in the current directory, that would have been interpreted as an option to rm, not as a file name to remove! Be careful with wildcards (and with file naming). If you have a file called -r in the current directory, the command ls * would list the other files in reverse order, and not show the '-r' file. In other words, if you had a file called --no-preserve-root, that would have been passed as an option to rm, not as a file name. Use rm -rf -- * to prevent that from happening, and also remove the files beginning with -. Or simply use absolute or relative path names to make the filenames begin with something other than -, as in: rm ./--flagfile or rm /abs/path/to/--flagfile. There is also a -i flag to rm that makes it prompt ("interactively") before removing anything.
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 options are available. You can check man page for that,
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 root directory of the Zip file. How can I print all the .doc files, in all the subdirectories?
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 the archive present in the local directory, then the command will only show top-level .doc files. With quotes, the argument is protected from the shell, so the wildcard actually makes it to zipinfo successfully.
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-a-directory-recursively) But I barely understand "piping" and am looking forward to seeing an example and clearing some uncertainties. I have this scenario in mind that I think would help me a lot to understand. Suppose I have this bash script snippet: for file in *.mkv *avi *mp4 *flv *ogg *mov; do target="${file%.*}.mkv" ffmpeg -i "$file" "$target" && rm -rf "$file" done What it does is, for the current directory, search for any *.mkv *avi *mp4 *flv *ogg *mov then declare the output to have its extension to be .mkv then afterwards delete the original file, then the output should be saved to the very same folder the original video is in. How can I convert this to run recursively? if I use find, where to declare the variable $file? And where should you declare $target? Are all find just really one-liners? I really need to pass the file to a variable $file, because I will still need to run the condition check. And, assuming that (1) is successful, how to make sure that the requirement "then the output should be save to the very same folder the original video is in" is satisfied?
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 find is very "un-UNIX-like" but the principle here is that each argument can be applied with AND or OR conditions. Here, we're going to say "If this-filename matches OR that-filename matches Then print-it". The filename patterns are quoted so that the shell can't get hold of them (remember that the shell is responsible for expanding all unquoted patterns, so if you had an unquoted pattern of *.mp4 and you had janeeyre.mp4 in your current directory, the shell would replace *.mp4 with the match, and find would see -name janeeyre.mp4 instead of your desired -name *.mp4; it gets worse if *.mp4 matches multiple names...). The brackets are prefixed with \ also to keep the shell from trying to action them as subshell markers (we could quote the brackets instead, if preferred: '('). find . \( -name '*.mkv' -o -name '*avi' -o -name '*mp4' -o -name '*flv' -o -name '*ogg' -o -name '*mov' \) -print The output of this needs to be fed into the input of a while loop that processes each file in turn: while IFS= read file ## IFS= prevents "read" stripping whitespace do target="${file%.*}.mkv" ffmpeg -i "$file" "$target" && rm -rf "$file" done Now all that's left is to join the two parts together with a pipe | so that the output of the find becomes the input of the while loop. While you're testing this code I'd recommend you prefix both ffmpeg and rm with echo so you can see what would be executed - and with what paths. Here is the final result, including the echo statements I recommend for testing: find . \( -name '*.mkv' -o -name '*avi' -o -name '*mp4' -o -name '*flv' -o -name '*ogg' -o -name '*mov' \) -print | while IFS= read file ## IFS= prevents "read" stripping whitespace do target="${file%.*}.mkv" echo ffmpeg -i "$file" "$target" && echo rm -rf "$file" done
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/" , "website.com/travels/[1994] Japan/", and so on... How can I download solely all ".mov" and ".jpg" that resides in all the subfolders only? I don't want to pick files from "travels/" (e.g. not "website.com/travels/list.doc") I found a wget command (on Unix&Linux Exchange, I don't remember what was the discussion) capable of downloading from subfolders only their "index.html", not others contents. Why download only index files?
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 more information. -P sets the directory prefix where all files and directories are saved to. -A sets a whitelist for retrieving only certain file types. Strings and patterns are accepted, and both can be used in a comma separated list (as seen above). See Types of Files for more information. If you would like to download subfolders you need to use the flag --no-parent, something similar to this command: wget -r -l1 --no-parent -P /save/location -A jpeg,jpg,bmp,gif,png,mov "http://www.somedomain.com" -r: recursive retrieving -l1: sets the maximum recursion depth to be 1 --no-parent: does not ascend to the parent; only downloads from the specified subdirectory and downwards hierarchy Regarding the index.html webpage. It will be excluded once the flag -A is included in the command wget, because this flag will force wget to download specific type of files, meaning if html is not included in the list of accepted files to be downloaded (i.e. flag A), then it will not be downloaded and wget will output in terminal the following message: Removing /save/location/default.htm since it should be rejected. wget can download specific type of files e.g. (jpg, jpeg, png, mov, avi, mpeg, .... etc) when those files are exist in the URL link provided to wget for example: Let's say we would like to download .zip and .chd files from this website In this link there are folders and .zip files (scroll to the end). Now, let's say we would like to run this command: wget -r --no-parent -P /save/location -A chd,zip "https://archive.org/download/MAME0.139_MAME2010_Reference_Set_ROMs_CHDs_Samples/roms/" This command will download .zip files and at the same time it will create an empty folders for the .chd files. In order to download the .chd files, we would need to extract the names of the empty folders, then convert those folder names to its actual URLs. Then, put all the URLs of interest in a text file file.txt, finally feed this text file to wget, as follows: wget -r --no-parent -P /save/location -A chd,zip -i file.txt The previous command will find all the chd files.
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-by-minute basis, that makes the above command near useless for finding files outside of the offending directory. I tried using the ls -I flag but to no avail: $ stat --printf="%y %n\n" $(ls -trI 'bad-dir' $(find * -type f)) Is there a simple way of excluding a single/specific directory using the ls command? Or should I be pushing the search into the find command?
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 check every file, if you want to ignore an entire subdirectory use -prune. You'll have to reorder things slightly so that we don't find all the files first. find . -path './directory/to/ignore' -prune -o -type f -print0 \ | xargs -0 stat --printf="%y %n\n" \ | sort -n And in the interests in being as efficient as possible, the stat was redundant, given find is already accessing the file. So you're actually hitting the filesystem 2X with the find ... | stat ... approach so here's a more efficient method that has find doing all the work. find . -path './directory/to/ignore' -prune -o -printf '%t %p\n' | sort -n To make this version work I've had to adapt the printf directives since stat and find use different ones for the various filesystem meta data. References find man page xargs man page sort man page
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 line folks know of a sweet way to do this, but I am still learning my way through it... Here's the commands I have aliased to brute force it: id3v2 --remove-frame "COMM" *.mp3 id3v2 --remove-frame "PRIV" *.mp3 id3v2 -s *.mp3 So -- is there a way to do this recursively, so I can run it a the root of my music folder? Gravy points for: including other audio file types and collapsing all three commands above into one uber command (I can do this with the ; between commands... right?)
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 shell. The -execdir runs until it hits a semi-colon, but the semi-colon (;) needs escaping from the shell, hence the use of the backslash (\). This is all described in the find manpage: -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. -execdir command {} + Like -exec, but the specified command is run from the subdirec‐ tory containing the matched file, which is not normally the directory in which you started find. This a much more secure method for invoking commands... Since you sound like you're a little new to this, a caveat: As always with complex shell commands, run them cautiously, and try in a test directory first, to make sure you understand what is going to happen. With great power comes great responsibility!
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 $ cp -r 1/* 2/* zsh: no matches found: 2/* $ cp -r 1/* 2/* $ mkdir 2/f $ mkdir 2/g $ cp -r 1/* 2/* $ tree . ├── 1 │   ├── a │   ├── b │   └── c │   └── x └── 2 ├── f └── g ├── a ├── b ├── c │   └── x └── f 7 directories, 6 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 (except the last one) to 2/g. If you are intending to copy things to 2, the second glob isn't necessary, making the command cp -r 1/* 2/. If you are intending to copy things to multiple destinations, you can't specify that with just cp; you can use a small loop, like the following: #!/bin/sh for path in ./2/*/; do cp -r 1/* "$path" done
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 group for all his files/subdirectories, instead of my username. The issue is that there are a couple of subdirectories whose group is "docker". Inside these subdirectories, there are some files/directories whose group is my username, and some other files/directories whose group is "docker". How do I recursively run chgrp on his home directory so that every single file/subdirectory whose group is my username gets changed to his username, but every single file/subdirectory whose group is "docker" stays "docker"?
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 appropriate.
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 /root/newdir /root/newdir/1 /root/newdir/2 /root/newdir/3 /root/newdir/4 /root/newdir/5 /root/newdir/newdir2 /root/newdir/newdir2/1 /root/newdir/newdir2/2 /root/newdir/new /root/newdir/dir /root/newdir/new dir When I try this with md5 I get two different outcomes, neither of which work: c5-26-1# md5 $(find /root/newdir) # same outcome using for loop MD5 (/root/newdir) = bc79a580f6c932937f6fcd454747db72 MD5 (/root/newdir/1) = 94ca98295946310ce88e185ea57486d5 MD5 (/root/newdir/2) = 8432051f64459be5a5e73dc2abd91795 MD5 (/root/newdir/3) = d41d8cd98f00b204e9800998ecf8427e MD5 (/root/newdir/4) = d41d8cd98f00b204e9800998ecf8427e MD5 (/root/newdir/5) = d41d8cd98f00b204e9800998ecf8427e MD5 (/root/newdir/newdir2) = 722165901468b9596dbdddfe118759fb MD5 (/root/newdir/newdir2/1) = d41d8cd98f00b204e9800998ecf8427e MD5 (/root/newdir/newdir2/2) = d41d8cd98f00b204e9800998ecf8427e MD5 (/root/newdir/new) = 89d042c5f9d6ba485a654b543685ea86 MD5 (/root/newdir/dir) = 148538718feba14839f5d1072854c5f4 MD5 (/root/newdir/new) = 89d042c5f9d6ba485a654b543685ea86 MD5 (dir) = 148538718feba14839f5d1072854c5f4 or c5-26-1# find -X /root/newdir | xargs md5 find: /root/newdir/new dir: illegal path MD5 (/root/newdir) = bc79a580f6c932937f6fcd454747db72 MD5 (/root/newdir/1) = 94ca98295946310ce88e185ea57486d5 MD5 (/root/newdir/2) = 8432051f64459be5a5e73dc2abd91795 MD5 (/root/newdir/3) = d41d8cd98f00b204e9800998ecf8427e MD5 (/root/newdir/4) = d41d8cd98f00b204e9800998ecf8427e MD5 (/root/newdir/5) = d41d8cd98f00b204e9800998ecf8427e MD5 (/root/newdir/newdir2) = 722165901468b9596dbdddfe118759fb MD5 (/root/newdir/newdir2/1) = d41d8cd98f00b204e9800998ecf8427e MD5 (/root/newdir/newdir2/2) = d41d8cd98f00b204e9800998ecf8427e MD5 (/root/newdir/new) = 89d042c5f9d6ba485a654b543685ea86 MD5 (/root/newdir/dir) = 148538718feba14839f5d1072854c5f4 How do I account for directories with spaces?
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 shell that would require quoting. If your implementation of find is reasonably current, then you can make it do what xargs is famous for, which is to invoke the md5 program once per batch of arguments. find /root/newdir -type f -exec md5 {} + If your find doesn't support -exec … {} +, replace the + by \;. This makes find invoke md5 for each file in turn. It's slightly slower, but available everywhere.
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 change the strace source code, such that -P 0 means, ask user for PID. E.g., read() from STDIN. When we can run two strace processes in two shell sessions and find the PIDs in a third shell, we can provide that input to S1 & S2 and let them monitor each other. Would S1 & S2 get stuck? Or, go into infinite loops, or crash immediately or...? Again, let us say we have another strace process S3, with -p -1, which, by modifying the source code, we use to tell S3 to monitor itself. E.g., use getpid() without using STDIN. Would S3 crash? Or, would it hang with no further processing possible? Would it wait for some event to happen, but, because it is waiting, no event would happen? In the strace man-page, it says that we can not monitor an init process. Is there any other limitation enforced by strace, or by the kernel, to avoid a circular dependency or loop? Some Special Cases : S4 monitors S5, S5 monitors S6, S6 monitors S4. S7 & S8 monitoring each other where S7 is the Parent of S8. More special cases are possible. EDIT (after comments by @Ralph Rönnquist & @pfnuesel) : https://github.com/bnoordhuis/strace/blob/master/strace.c#L941 if (pid <= 0) { error_msg_and_die("Invalid process id: '%s'", opt); } if (pid == strace_tracer_pid) { error_msg_and_die("I'm sorry, I can't let you do that, Dave."); } Specifically, what will happen if strace.c does not check for pid == strace_tracer_pid or any other special cases? Is there any technical limitation (in kernel) over one process monitoring itself? How about a group of 2 (or 3 or more) processes monitoring themselves? Will the system crash or hang?
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 insufficient privileges (the required capability is CAP_SYS_PTRACE); unprivileged processes cannot trace pro‐ cesses that they cannot send signals to or those running set- user-ID/set-group-ID programs, for obvious reasons. Alterna‐ tively, the process may already be being traced, or (on kernels before 2.6.26) be init(8) (PID 1). implying that starting in version 2.6.26, you can trace init, although of course you must still be root in order to do so. The strace binary on my system allows me to trace init, and in fact I can even use gdb to attach to init and kill it. (When I did this, the system immediately came to a halt.) ptrace cannot be used by a process to trace itself, so if strace did not check, it would nevertheless fail at tracing itself. The following program: #include <sys/ptrace.h> #include <stdio.h> #include <unistd.h> int main() { if (ptrace(PTRACE_ATTACH, getpid(), 0, 0) == -1) { perror(NULL); } } prints Operation not permitted (i.e., the result is EPERM). The kernel performs this check in ptrace.c: retval = -EPERM; if (unlikely(task->flags & PF_KTHREAD)) goto out; if (same_thread_group(task, current)) // <-- this is the one goto out; Now, it is possible for two strace processes can trace each other; the kernel will not prevent this, and you can observe the result yourself. For me, the last thing that the first strace process (PID = 5882) prints is: ptrace(PTRACE_SEIZE, 5882, 0, 0x11 whereas the second strace process (PID = 5890) prints nothing at all. ps shows both processes in the state t, which, according to the proc(5) manual page, means trace-stopped. This occurs because a tracee stops whenever it enters or exits a system call and whenever a signal is about to be delivered to it (other than SIGKILL). Assume process 5882 is already tracing process 5890. Then, we can deduce the following sequence of events: Process 5890 enters the ptrace system call, attempting to trace process 5882. Process 5890 enters trace-stop. Process 5882 receives SIGCHLD to inform it that its tracee, process 5890 has stopped. (A trace-stopped process appears as though it received the `SIGTRAP signal.) Process 5882, seeing that its tracee has made a system call, dutifully prints out the information about the syscall that process 5890 is about to make, and the arguments. This is the last output you see. Process 5882 calls ptrace(PTRACE_SYSCALL, 5890, ...) to allow process 5890 to continue. Process 5890 leaves trace-stop and performs its ptrace(PTRACE_SEIZE, 5882, ...). When the latter returns, process 5890 enters trace-stop. Process 5882 is sent SIGCHLD since its tracee has just stopped again. Since it is being traced, the receipt of the signal causes it to enter trace-stop. Now both processes are stopped. The end. As you can see from this example, the situation of two process tracing each other does not create any inherent logical difficulties for the kernel, which is probably why the kernel code does not contain a check to prevent this situation from happening. It just happens to not be very useful for two processes to trace each other.
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/ -not -path "*1*" -not -path "*2*" Output: test/ test/3 Great. So i combine it with tar: find test/ -not -path "*1*" -not -path "*2*" | tar -czvf test.tar.gz --files-from - Output: test/ test/3/ test/1/ test/foo2bar/ test/3/ Indeed, both "test/1" and "test/foo2bar" are present in the archive. Why were these arguments passed to tar, if they were not supposed to be present in find output?
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 --files-from - You could instead use the --no-recursion flag to tar: find test/ -not -path "*1*" -not -path "*2*" | tar -czvf test.tar.gz --no-recursion --files-from - Which results in: test/ test/3/ The --no-recursion flag is specific to GNU tar. If you're using something else, consult the appropriate man page to see if there is a similar feature available. Note that your find command will exclude files that contain 1 or 2 in the path as well as directories.
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 initially introduced a -print0 predicate and a -0 option to xargs instead for that: find /path/to/parent -type f -print0 | xargs -0 grep 'XXX' /dev/null There are now a few other implementations that support that, but not Solaris. Above, in theory, you'd want to add -r option to avoid running grep if there's not file, but that's not as portable and in this particular case, doesn't make a functional difference
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/image1.jpg /content1/images/image2.jpg /content1/background/spacer.gif /content1/background/background.gif /content2/index.php /content2/images/image3.jpg /content2/background/spacer.gif /content2/background/background.gif Then I want /content1/images/image1.jpg /content1/images/image2.jpg /content1/background/spacer.gif /content1/background/background.gif /content2/images/image3.jpg /content2/background/spacer.gif /content2/background/background.gif I can use the find command to get a list of only image files, but I don't know how to manipulate each file while preserving the directory path to it. I could make a copy of the entire directory, and then recursively delete any non-image file, but now that I have set this problem before myself, I figure its worthwhile to know how to do it, in case I really do need to do it this way later.
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 wish I could download them as well. Is it possible to do so with wget? Are there any flags for that?
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 ccc in your example). k Convert links relative to local copy. p Get page-requisites like stylesheets (this is an exception to the np rule). If I remember correctly, wget will create a directory named after the domain and put everything in there, but just in case try it from an empty PWD.
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" --> "$i ./$0 $i $2 done exit 0 fi echo "Target "$1" just received command '"$2"'" exit 0 I expect the following output: $ recur all boggle boggle --> aaa Target aaa just received command 'boggle' boggle --> bbb Target bbb just received command 'boggle' boggle --> ccc Target ccc just received command 'boggle' boggle --> ddd Target ddd just received command 'boggle' But the script exits at the first iteration: $ recur all boggle boggle --> aaa Target aaa just received command 'boggle'
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 #!/bin/bash # recur.sh targets=('aaa' 'bbb' 'ccc' 'ddd') if [ "$1" == "all" ] ; then for i in ${targets[@]}; do echo $2" --> "$i ./$0 $i $2 done exit 0 fi echo "Target "$1" just received command '"$2"'" exit 0
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 first), xargs (in the second) will pass as many arguments to grep as possible without exceeding the limit on the number of arguments you can pass to a command. When doing that splitting, it could happen that for the last run, only one argument be passed to grep in which case grep wouldn't print the file name. That's why you need /dev/null there (or -H with GNU grep). With -type f, we're only considering regular files (not devices, symlinks, pipes, directories...). If you want to use GNUisms, you could use GNU grep ability to descend a directory tree: grep -rHnF --include='CMake*' version . You don't want to use -R as that causes grep to follow symlinks when descending the directory tree and read from devices, fifos, sockets... That version is safer and more efficient, but not portable.
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 │   └── file3 ├── dvd │   ├── 0 │   │   ├── file1 │   │   ├── file2 │   │   └── file3 │   ├── 1 │   │   ├── file1 │   │   ├── file2 │   │   └── file3 │   └── 2 │   ├── file1 │   ├── file2 │   └── file3 └── stuff ├── 0 │   ├── file1 │   ├── file2 │   └── file3 ├── 1 │   ├── file1 │   ├── file2 │   └── file3 └── 2 ├── file1 ├── file2 └── file3 I've changed the files in my branch 2, and I need to apply them to branch 1. If I just try moving them over branch 1, I get the following errors: mv: cannot move `/branch2/media/cd' to `/branch1/media/cd': Directory not empty. Is there another command I should be using for this? mv -f doesn't seem to do the trick.
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 package I need to use on Ubuntu to achieve this?
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 directory. I'm scared to go for rmdir or rm -rf because I'm not sure what will be attempted to be deleted, the link or folder2. This is especially an issue since folder1/folder2 is a shared folder and I don't want to mess this up for other users on the server.
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 link.
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 replace string /*Comment*/ with a couple normal words, what delimiters should I use, so that sed works properly?
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 folder or file but I need it to traverse a directory.
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 that has some limitations on some systems/configurations). The longer story Let's consider what it takes for instance for a $user to have read access to /foo/file.txt (assuming none of /foo and /foo/file.txt are symlinks)? He needs: search access to / (no need for read) search access to /foo (no need for read) read access to /foo/file.txt You can see already that approaches that check only the permission of file.txt won't work because they could say file.txt is readable even if the user doesn't have search permission to / or /foo. And an approach like: sudo -u "$user" find / -readable Won't work either because it won't report the files in directories the user doesn't have read access (as find running as $user can't list their content) even if he can read them. If we forget about ACLs or other security measures (apparmor, SELinux...) and only focus on traditional permission and ownership attributes, to get a given (search or read) permission, that's already quite complicated and hard to express with find. You need: if the file is owned by you, you need that permission for the owner (or have uid 0) if the file is not owned by you, but the group is one of yours, then you need that permission for the group (or have uid 0). if it's not owned by you, and not in any of your groups, then the other permissions apply (unless your uid is 0). In find syntax, here as an example with a user of uid 1 and gids 1 and 2, that would be: find / -type d \ \( \ -user 1 \( -perm -u=x -o -prune \) -o \ \( -group 1 -o -group 2 \) \( -perm -g=x -o -prune \) -o \ -perm -o=x -o -prune \ \) ! -type d -o -type l -o \ -user 1 \( ! -perm -u=r -o -print \) -o \ \( -group 1 -o -group 2 \) \( ! -perm -g=r -o -print \) -o \ ! -perm -o=r -o -print That one prunes the directories that user doesn't have search right for and for other types of files (symlinks excluded as they're not relevant), checks for read access. Or for an arbitrary $user and its group membership retrieved from the user database: groups=$(id -G "$user" | sed 's/ / -o -group /g'); IFS=" " find / -type d \ \( \ -user "$user" \( -perm -u=x -o -prune \) -o \ \( -group $groups \) \( -perm -g=x -o -prune \) -o \ -perm -o=x -o -prune \ \) ! -type d -o -type l -o \ -user "$user" \( ! -perm -u=r -o -print \) -o \ \( -group $groups \) \( ! -perm -g=r -o -print \) -o \ ! -perm -o=r -o -print The best here would be to descend the tree as root and check the permissions as the user for each file. find / ! -type l -exec sudo -u "$user" sh -c ' for file do [ -r "$file" ] && printf "%s\n" "$file" done' sh {} + Or with perl: find / ! -type l -print0 | sudo -u "$user" perl -Mfiletest=access -l -0ne 'print if -r' Or with zsh: files=(/**/*(D^@)) USERNAME=$user for f ($files) { [ -r $f ] && print -r -- $f } Those solutions rely on the access(2) system call. That is instead of reproducing the algorithm the system uses to check for access permission, we're asking the system to do that check with the same algorithm (which takes into account permissions, ACLs...) it would use would you try to open the file for reading, so is the closest you're going to get to a reliable solution. Now, all those solutions try to identify the paths of files that the user may open for reading, that's different from the paths where the user may be able to read the content. To answer that more generic question, there are several things to take into account: $user may not have read access to /a/b/file but if he owns file (and has search access to /a/b, and he's got shell access to the system), then he would be able to change the permissions of the file and grant himself access. Same thing if he owns /a/b but doesn't have search access to it. $user may not have access to /a/b/file because he doesn't have search access to /a or /a/b, but that file may have a hard link at /b/c/file for instance, in which case he may be able to read the content of /a/b/file by opening it via its /b/c/file path. Same thing with bind-mounts. He may not have search access to /a, but /a/b may be bind-mounted in /c, so he could open file for reading via its /c/file other path. To find the paths that $user would be able to read. To address 1 or 2, we can't rely on the access(2) system call anymore. We could adjust our find -perm approach to assume search access to directories, or read access to files as soon as you're the owner: groups=$(id -G "$user" | sed 's/ / -o -group /g'); IFS=" " find / -type d \ \( \ -user "$user" -o \ \( -group $groups \) \( -perm -g=x -o -prune \) -o \ -perm -o=x -o -prune \ \) ! -type d -o -type l -o \ -user "$user" -print -o \ \( -group $groups \) \( ! -perm -g=r -o -print \) -o \ ! -perm -o=r -o -print We could address 3 and 4, by recording the device and inode numbers or all the files $user has read permission for and report all the file paths that have those dev+inode numbers. This time, we can use the more reliable access(2)-based approaches: Something like: find / ! -type l -print0 | sudo -u "$user" perl -Mfiletest=access -0lne 'print 0+-r,$_' | perl -l -0ne ' ($w,$p) = /(.)(.*)/; ($dev,$ino) = stat$p or next; $writable{"$dev,$ino"} = 1 if $w; push @{$p{"$dev,$ino"}}, $p; END { for $i (keys %writable) { for $p (@{$p{$i}}) { print $p; } } }' And merge both solutions with: { solution1; solution2 } | perl -l -0ne 'print unless $seen{$_}++' As should be clear if you've read everything thus far, part of it at least only deals with permissions and ownership, not the other features that may grant or restrict read access (ACLs, other security features...). And as we process it in several stages, some of that information may be wrong if the files/directories are being created/deleted/renamed or their permissions/ownership modified while that script is running, like on a busy file server with millions of files. Portability notes All that code is standard (POSIX, Unix for t bit) except: -print0 is a GNU extension now also supported by a few other implementations. With find implementations that lack support for it, you can use -exec printf '%s\0' {} + instead, and replace -exec sh -c 'exec find "$@" -print0' sh {} + with -exec sh -c 'exec find "$@" -exec printf "%s\0" {\} +' sh {} +. perl is not a POSIX-specified command but is widely available. You need perl-5.6.0 or above for -Mfiletest=access. zsh is not a POSIX-specified command. That zsh code above should work with zsh-3 (1995) and above. sudo is not a POSIX-specified command. The code should work with any version as long as the system configuration allows running perl as the given user.
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 movie.nfo, then I want to copy that directory and its contents to the external drive. I've tried this: find . -name "*.avi" -printf "%h\n" -exec cp {} /share/USBDisk1/Movies/ \; But it only copies the file, not the directory and file contents.
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 in that cp command, you need to modify the file name before passing it to cp. The find command doesn't have this capability, but a shell does, so make find invoke a shell which invokes cp. find . -name "*.avi" -exec sh -c 'cp -Rp "${0%/*}" /share/USBDisk1/Movies/' {} \; Note that you'll need to pass -r to cp since you're copying a directory. You should probably preserve metadata such as the files' modification time, too, with -p. You may usefully replace cp -Rp by rsync -a. That way, if you've already copied a movie directory, it won't be copied again (unless its contents have changed). Your command has a defect that may or may not affect you: if a directory contains multiple .avi files, it will be copied multiple times. It would be better to look for directories, and copy them if they contain a .avi file, rather than look for .avi files. If you use rsync instead of cp, the files won't be copied again, it's just a bit more work for rsync to verify the existence of the files over and over. If all the movie directories are immediately under the toplevel directory, you don't need find, a simple loop over a wildcard pattern suffices. for d in ./*/; do set -- "$d/"*.avi if [ -e "$1" ]; then # there is at least one .avi file in $d cp -rp -- "$d" /share/USBDisk1/Movies/ fi done If the movie directories may be nested (e.g. Movies/science fiction/Ridley Scott/Blade Runner), you don't need find, a simple loop over a wildcard pattern suffices. You do need to be running ksh93 or bash ≥4 or zsh, and in ksh93 you need to run set -o globstar first, and in bash you need to run shopt -s globstar first. The wildcard pattern **/ matches the current directory and all its subdirectories recursively (bash also traverses symbolic links to subdirectories). for d in ./**/; do set -- "$d/"*.avi if [ -e "$1" ]; then cp -rp -- "$d" /share/USBDisk1/Movies/ fi done
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 same folder. They should ofcourse be renamed and I have tried to use --backup for that... I have tried find files_input -name \*.html -exec cp --backup=t '{}' files_output \; to get them numbered but that copies only one file and nothing else. I don't know does that change anything but I'm using zsh, here are the versions: $ zsh --version | head -1 zsh 5.0.2 (x86_64-pc-linux-gnu) $ bash --version | head -1 GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu) $ cp --version | head -1 cp (GNU coreutils) 8.21 $ find --version | head -1 find (GNU findutils) 4.4.2 Ideas? Edit: Trying to run e.g. following cp --backup=t files_input/01-2015/index.html files_output five times in a row still gives me one index.html in files_output folder! Is cp broken ? Why don't I have five different files?
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 | | `-- index.html | |-- subfolder-2 | | `-- index.html | |-- subfolder-3 | | `-- index.html | |-- subfolder-4 | | `-- index.html | `-- subfolder-5 | `-- index.html (etc.) $ mkdir -p files_output $ autoload -U zmv $ zmv -C './files_input/(*)/(*)/index.html' './files_output/$1-$2-index.html' $ tree files_output files_output |-- 01_2015-subfolder-1-index.html |-- 01_2015-subfolder-2-index.html |-- 01_2015-subfolder-3-index.html |-- 01_2015-subfolder-4-index.html |-- 01_2015-subfolder-5-index.html |-- 02_2015-subfolder-1-index.html |-- 02_2015-subfolder-2-index.html (etc.) What's happening here is that we make the command zmv available with autoload -U zmv. This command is used for renaming, copying or linking files matching a zsh extended globbing pattern. We use zmv with its -C option, telling it to copy the files (as opposed to moving them, which is the default). We then specify a pattern that matches the files we'd want to copy, ./files_input/(*)/(*)/index.html. The two (*) matches the two levels of subdirectory names, and we put them within parentheses for use in the new name of each file. The new name of each file is the second argument, ./files_output/$1-$2-index.html, where $1 and $2 will be the strings captured by the parentheses in the pattern, i.e. back-references to the subdirectory names. Both arguments should be single quoted.
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/catpictures/or.aaa' `some_folder/catpictures/on.bub' -> `some_folder/catpictures/on.aaa' ... which you could generalise to a bash function: $ extmv () { find "${1}" -type f -name "*.${2}" | sed "s/\.${2}$//" | xargs -I% mv -iv "%.${2}" "%.${3}" } ... which you'd use like this: $ extmv some_folder/ bub aaa
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 -type f -exec ls -l {} \; and got the same result as warl0ck and pradeepchhetri offered.
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 want files executable only by you, that's okay to use -executable.
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 instead of iterating over the output.
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 available in other shells.
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 can change them to my new user name? I want to exclude the files which shows some other owners like 501. Edit: Example: ls -l total 3 -rw-rw-r--. 1 500 500 210 Jan 10 2012 about.xml drwxr-xr-x. 2 500 500 4096 May 15 2013 apache drwxrwxr-x. 2 500 500 4096 Dec 9 2012 etc Now, I can do chown -R xyz:xyz . to make them look like: ls -l total 3 -rw-rw-r--. 1 xyz xyz 210 Jan 10 2012 about.xml drwxr-xr-x. 2 xyz xyz 4096 May 15 2013 apache drwxrwxr-x. 2 xyz xyz 4096 Dec 9 2012 etc But I just want to know if there are some kind of commands which can map user 500 to user "xyz". Thank you.
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 inside that tree were owned by many different users, but you're only interested in updating those that were owned by "your" user at the moment, and not any of the files that are owned by user #501 or any other. GNU chown supports an option --from=500 that you can use in combination with the -R recursive option to do this: chown -R --from=500 yourusername /path/here This will be the fastest option if you have GNU chown, which on CentOS you should. Alternatively can use find on any system: find /path/here -user 500 -exec chown yourusername '{}' '+' find will look at every file and directory recursively inside /path/here, matching all of those owned by user #500. With all of those files, it will execute chown yourusername file1 file2... as many times as required. After the command finishes, all files that were owned by user #500 will be owned by yourusername. You'll need to run that command as root to be able to change the file owners. You can check for any stragglers by running the same find command without a command to run: find /path/here -user 500 It should list no files at this point. An important caveat: if any of the files owned by user #500 are symlinks, chown will by default change the owner of the file the symlink points at, not the link itself. If you don't trust the files you're examining, this is a security hole. Use chown -h in that case.
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-directory has been renamed resulting in a "No such file or directory" Command: rename -f 's/foo/bar/' ** rename -f 's/Foo/Bar/' ** For example, here is an original file that I would like to replace 'foo' with 'bar' File: /test/foo/com/test/foo/FooMain.java Failure: Can't rename /test/foo/com/test/foo/FooMain.java /test/bar/com/test/foo/FooMain.java: No such file or directory Preferred File: /test/bar/com/test/bar/BarMain.java You can see from the error message that it's attempting to rename the parent directory but at that point the subdirectory has already been changed resulting in the file not found error. Is there parameters for the rename command that will fix this or do I need to go about this in a different way?
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 -iname '*foo*' -execdir rename -- 's/Foo/Bar/;s/foo/bar/' {} + results in $ tree . └── dir ├── bar │   └── baz │   └── MainBar.c └── Bar ├── baz └── MainBar.c 5 directories, 2 files
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 counter ./$file fi done } counter $1
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 to some other directory to traverse.
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 end (so I would be able to compute the read speed //cache doesn't matter//) and/or show each file's size beside it's name. If there would be possibility to show progress for each file (pv) - that would be great! For this purpose I'm using Cygwin and it's bash shell, but script should also work on real Linux systems. EDIT: The idea is to read the files, not to copy them (rsync).
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 or more letters from the set rwxXst, or a single letter from the set ugo.  …                 ︙ The letters rwxXst select ….  Instead of one or more of these letters, you can specify exactly one of the letters ugo: the permissions granted to the user who owns the file (u), the permissions granted to other users who are members of the file’s group (g), and the permissions granted to users that are in neither of the two preceding categories (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 does not copy any file with a : in it. This post gives a solution for a single file: rsync: colon in file names, but the problem is that I have so many of these files scattered in different directories that I cannot do it manually. Is there any way to recursively rsync any files with a colon in the filename?
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 size. Another possibility would be to use rdiff-backup, which takes care of translating file names that don't fit on the destination filesystem, as suggested by poolie. A generic approach to unsupported characters is to leverage the filesystem layer to transform the file names. The FUSE filesystem posixovl transforms file names into names that Windows's VFAT supports. mkdir ~/mnt mount.posixovl -S /media/extern_drive ~/mnt rsync -a /work ~/mnt fusermount -u ~/mnt See How can I substitute colons when I rsync on a USB key? for more details, and check that thread for any new solution that may come up.
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 {print count}' Just to make it clear this is an example: FILE_1 2 345 123 4 2 4567 2344 6 3 2345 657 87 6 234 345 6 FILE_2 1 12 436 7 2 54 86 8 2 23 48 0 2 098 0 8 8 98 9 0 PRINT: FILE_1 2 FILE_2 3 What I'm actually getting: PRINT: 5 Thanks for your help!
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 2. Note: If the "40 files" you're looking for are all in the same directory (not in sub-directories), you can make find search the current directory only without recursing (so that you get less latency) like so: find -maxdepth 1 . -type f -print0 Update: To match files where the 2 occurs in a different column to the first, you can do this: COLNUM=3 TOMATCH=$(($COLNUM-1)) grep -cE "^[[:space:]]*([0-9]+[[:space:]]+){$TOMATCH}2\>" \ $(find . -type f -print0 | xargs -0 echo) You can change COLNUM as needed. Basically, what this does is, it attempts to match COLNUM-1 columns followed by a 2 at a word boundary. The -E switch is needed to enable extended regular expressions which allows you to use the {} notation to specify a numerical quantifier (i.e. 'match the previous pattern this many times'). Note however,that if you enter a column number that doesn't exist in the file the regex will fail silently.
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 on being stupid with my directory structure, the deepest I may go is 1-2 MAYBE 3. Thus far I have: # A Makefile to build our First_Game_2 project dirs = * */parse PROJECT = main HEADERS = $(PROJECT).h OBJ = $(foreach dirz, $(dirs), \ \ $(patsubst %.c,%.o,$(wildcard $(dirz).c)) \ \ ) C99 = gcc -std=c99 CFLAGS = -Wall -pedantic -Werror $(PROJECT) : $(OBJ) $(C99) $(CFLAGS) -o $(PROJECT) $(OBJ) %.o : %.c $(HEADERS) $(C99) $(CFLAGS) -c $< clean: rm -f $(PROJECT) $(OBJ) My problem is if parse contains a subfolder, say test to give the structure PROJECT_FOLDER/parse/test In such a case, nothing is returned from $(foreach dirz, $(dirs), \ \ $(patsubst %.c,%.o,$(wildcard $(dirz).c)) \ \ ) I tested the output of the function with the following makefile # A Makefile to build our First_Game_2 project dirs = * */parse PROJECT = main HEADERS = $(PROJECT).h OBJ = C99 = gcc -std=c99 CFLAGS = -Wall -pedantic -Werror $(foreach dirz, $(dirs), \ \ $(patsubst %.c,%.o,$(wildcard $(dirz).c)) \ \ ) Which, given a structure of: dirs = * */parse */parse/test Produces an output of: main.o parse/parse.o Ignoring */parse/test Why is this the case, what can I do to fix my OBJ assignment to recognize */parse/test or otherwise?
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 directory is because you used the same filename, 'parse', as the directory name.
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 is not what I was expecting, it's value doesn't change. for source in `find $1 -maxdepth 1 -type d,f` do if [ -f $source ]; then echo "`basename $source` is a file" fi if [ -d $source ]; then echo "`basename $source` is a directory" . Script.sh $source fi done
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, better yet: "$0" "$source" Reliably getting the source script in all cases is a bit tricky, though. Much better yet is to use functions to do recursion (in Bash): function f() { ... f different_args ... } And declare any variables used within f as local so they won't be mutated by the recursive call to f.
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 zip files within zip files?
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 actual problem, see How do I recursively grep through compressed archives?
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 . -name *.mp4); do ffmpeg -i "$video" -acodec aac -ac 2 "${video%.*}".mkv; rm "$video"; done But this seems to fail on folders with spaces in them. Can anyone point out my error?
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 what your loop will iterate over, which is not what you want. Your loop that works for the current directory (fixing the issue with filenames starting with a dash): for video in ./*.mkv; do ffmpeg -i "$video" -acodec aac -ac 2 "${video%.*}".mp4 rm "$video" done Changed to work recursively, by enabling the ** globbing pattern (and using nullglob to avoid running the loop at all if there are no matches): shopt -s globstar nullglob for video in ./**/*.mkv; do ffmpeg -i "$video" -acodec aac -ac 2 "${video%.*}".mp4 rm "$video" done The two loops above would not care about the filetype and would happily feed ffmpeg with symbolic links, directories, or any other non-regular type of file, as long as the name matched the given pattern. Alternatively, delegating the recursive generation of pathnames to find (also only selecting regular files): find . -name '*.mkv' -type f -exec sh -c ' for video do ffmpeg -i "$video" -acodec aac -ac 2 "${video%.*}".mp4 rm "$video" done' sh {} + The above would also find hidden names matching the pattern, which the first two shell loops would not do (unless you enable the dotglob shell option). Other relevant questions: Why is looping over find's output bad practice? Understanding the -exec option of `find`
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 will fail upon restarting. Is there any "index" or package which will enable reverting these permission to the right / previous ones? Here is the console output which help me realize and abort that operation: Can I do anything to recover?
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 command after a while. The system may not even boot anymore. Most of the services probably don't start anymore. I think, every system administrator had to learn that the hard way. That's why I have a some rules for myself: Always when doing a command with -R, re-read it at least 3 times, before pressing Enter. Then: Read it again. Sure? Press Enter (and keep the fingers crossed).
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/0b8 /mnt/originals.us/4/0b4 /mnt/originals.us/4/0b3 /mnt/originals.us/4/0b9/a62/ /mnt/originals.us/4/0b9/a47/ /mnt/originals.us/4/0b9/f0f/ /mnt/originals.us/4/0b9/a62/aa5/file16.png /mnt/originals.us/4/0b9/a62/ba1/file1.png /mnt/originals.us/4/0b9/a47/31f/file3.mov /mnt/originals.us/4/0b9/f0f/ . . . Etc. It is a pretty large set of files of different file names and types. I tried the following but it didn't work. mv /mnt/originals-us/ /mnt/originals/ but get the following mv: inter-device move failed: `/mnt/originals-us/10/0b9/' to `/mnt/originals/10/0b9'; unable to remove target: Is a directory I also thought about writing a massively chanin-ed command but I don't think that would work either. This is what I have so far. find . -type f -print | rev | cut -d '/' -f1 | rev This obviously gives me all the filenames but how do I chain it with the first part?
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 if that is available, then abort and warn the user or (if the space is adequate) perform the operation. EDIT: I omitted the recursion option (-r) by mistake, thanks to the OP for mentioning, now fixed
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 unintended havoc renaming the following items: ./.cache/google-chrome/Default/Storage/ext/nmmhkkegccagdldgiimedpiccmgmieda/def/Code Cache ./.cache/google-chrome/Default/Storage/ext/gfdkimpbcpahaombhbimeihdjnejgicl/def/Code Cache ./.cache/google-chrome/Default/Code Cache I would like my script to except any directory or file that starts with . from renaming it. How would you write such a script? Does one need to use regular expressions for this purpose?
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 with -depth) we don't need to call dirname/basename (which would be expensive and not work properly with command substitution if there are some file names ending in newline characters). it doesn't have find problems whereby * don't match arbitrary sequences of bytes. If there are some conflicts (like when there's both a a b c and a_b c files which would both be renamed to a_b_c), it will detect it at the start and abort before doing any rename. To do something approaching with GNU tools, that would be something like: #! /bin/bash - export LC_ALL=C while IFS= read <&3 -rd '' file; do dir=${file%/*} name=${file##*/} mv -i -- "$file" "$dir/${name// /_}" done 3< <( find . -name '.?*' -prune -o -name '* *' -print0 | tac -s '') Here, setting the locale to C so * matches any sequence of bytes, not just those forming valid characters in the user's locale, and ? matches a single byte. Beware though that the messages (errors, prompts...) will then be issued in English instead of the user's language. -name '.?*' -prune -o ... skips hidden files and tells find not to descend into hidden directories. Passing -i to mv to guard against clobbering files unintentionally. Passing the list of files over fd 3 instead of stdin, so mv -i prompt works. Using tac -s '' instead of sort -rz to reverse the output to ensure leaves are renamed before the branches they're on. replacing dirname/basename with the standard ${var##pattern} and ${var%pattern} parameter expansion operators. also passing -r to read to disable its special handling of backslashes. making sure that for read $IFS is empty, so it doesn't remove trailing white space from the input records.
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 of files within a complex directory structure where it bogs down and hangs. While I could work around and simply do the command at lower levels and work up piece by piece, I was wondering if there is a more efficient way to do this in one fell swoop?
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+) *\*/ (.*)" . | xargs sed -i "s/\/\* *(\d+) *\*\/ (.*)/$2 \/\/ JD $1/g" This regex is very confusing because it contains a lot of escaped asterisks and slashes, but essentially it takes in the string (for example) /* 73 */ private static int last = -1000; and replacing it with private static int last = -1000; // JD 73 However, as I said earlier, it simply does not work, and the files are unchanged. It works fine with an alternate regex that does not utilize capture groups grep -rl "/\* *\*/ " . | xargs sed -i "s/\/\* *\*\/ //g" but as soon as I try to introduce capture groups, it just silently fails. I can tell it's searching through the files, as I can hear the drive spin up for a moment like with the successful one, but in the end the files remain unchanged. Could it be possible to modify the command such that it works, or must I do it in a completely different way? Also, ideally the solution wouldn't require a bash loop. Thanks.
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 with [[:digit:]] or [0-9]+ Replace the backreferences $1 with \1 and $2 with \2 I think you can safely remove the g, JD only creates one comment at the beginning of the line. grep -Erl '/\* *[[:digit:]]+ *\*/' . | xargs sed -Ei 's/\/\* *([[:digit:]]+) *\*\/ (.*)/\2 \/\/ JD \1/'
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. To be more precise: I do not want to zip all *.txt files, but all directories that exclusively contain txt-files into a directory.zip and delete the original directory.
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 read folder; do echo "will remove $folder" # Uncomment next line for the folder to be removed # rm -rf "$folder" done Edit: here is a solution that creates individual zip files: find . -depth -type d -exec sh -c ' cd "$1" || exit [ "$(ls ./*.txt 2>/dev/null)" ] && [ -z "$(ls -ad ./* | grep -v '\.txt$')" ] && ( b=$(basename "$1") cd .. zip -r "$b.zip" "$b" && rm -rf "$b" )' sh {} \;
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/JSignPdf.jar *.pdf -a ...which of course works great for all PDF files in the current directory. How can I make it so it picks up all .pdf files in all the subdirectories as well? I've tried a few things which haven't worked... novice and not even worth mentioning...things like -r (obviously would-/did-n't work). I'm wondering if this is a simple answer or in need of some awk magic, if that would even be valid. Any help is greatly appreciated.
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 big, you could do: find . -name '*.pdf' -exec sh -c ' exec java -jar ../jsignpdf-1.4.3/JSignPdf.jar "$@" -a' sh {} + But beware find may try to split the list and run several sh commands to try and overcome a limit on the command line size.
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 existing examples but none I've tried have worked completely. edit --- for bonus points, this only happens for files that contain import React as this makes the refactor quite quicker with less manual checking.
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 Points Aspect Per the subsequent edit, to limit the renames just to those files which include a 'import React' line, use the solution below as suggested by @Robert Smith. find . -iname "*.js" -exec grep -q 'import React' {} \; -exec mv "{}" "{}x" \;
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 /path/to/dir/bar/foo How can I match paths for arbitrary depth that is under the directory /path/to/dir and has the file name foo?
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 subdirectories. [...] This form does not follow symbolic links; the alternative form '***/' does, but is otherwise identical. This also means that ** doesn't include hidden directories (whose name starts with a dot) by default. If you want to match them, either set the GLOB_DOTS option or use the D glob qualifier: grep some_pattern /path/to/dir/**/foo(D) With bash, you need to explicitly set the globstar option to make ** work: shopt -s globstar
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) What is the easiest way to do this task? For the sake of proving I thought about this somewhat, I would write a Perl script that took as input a single fully qualified filename and a regex pattern, and process the lines using the approximate Perl below (I haven't tried yet, but this is what my first attempt would resemble): while (<FILE>) { $line_number++; if ($_ =~ m/regex_pattern/) { # output: file_name\tline_number\tregex_pattern\t$_ # ignore escaping issues for the time being } } I'm still not sure how I'd pass in the contents of each directory with a recursive search into this Perl script. I can do the searching in Perl but I'm sure there's a nice Unix/Linux way to do this. I'm not married to Perl. If there's a way to do it chaining together standard Unix/Linux tools, that'd be awesome. If not, I prefer to use Perl as I'm somewhat familiar with it's syntax.
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/mdft/ takes hours and installs a ton of other stuff I didn't want that ISN'T contained in this folder: http://cl.ly/ENKr Moreover opening a particular page, many of the images are missing: http://cl.ly/ELXG This may be because I aborted the transfer after a few hours(!) How do I do this properly?
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/stylesheet.css">\' $i; \ done But the following command will not work. find . -type d -exec \ for i in *.html; \ do sed -i '/<head>/a <link rel="stylesheet" href="/home/jian/postgres/doc/src/sgml/html/stylesheet.css">\' $i; \ done \ \; It gives the following error: bash: syntax error near unexpected token `do' bash: syntax error near unexpected token `done' ;: command not found I found a related post here.
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 is invoked as few times as possible. Alternatively, shopt -s globstar dotglob failglob sed -i '...expression...' ./**/*.html This enables the ** pattern which works like * but matches across / in pathnames ("recursively"). It also allows patterns to match hidden names (like find would also do), and tells the shell to fail with an error if no names matches a pattern. The difference here is that The filetype of matching files is not tested (the pattern may match directories etc.) If the pattern matches many thousands of names, the command will fail to execute with a "Argument list too long" error.
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+ subdirectories sudo mv **/*.txt ~/Desktop/tmpremo/ Instead I am getting this error: bash: /usr/bin/sudo: Argument list too long Why am I getting it and how do I remove say .txt,.txt.exe? How do I fix it?
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' before the -exec. PS: As @xenoid noted, please refrain from using sudo unless it is absolutely required for the task at hand.
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 -0 chmod 600 && find . -type d -print0 | xargs -0 chmod 700
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 result in : drwx------ 1/ drwx------ 2/ drwx------ 3/ -rw------- 4 -rw------- 5 -rw------- 6 Compared to find and xargs, this has the advantage of requiring one command only, and therefore no pipe. For this reason, I would be inclined to say that this is faster. In your example, you are basically using two commands in one line: The first searches files, prints their names and xargs does the rest. The second searches directories, same behaviour. In each of these calls, you run three commands: Run find so that it prints out the names of the files you're interested in. Pass these names to xargs so it acts as a wrapper around chmod (which is, therefore, called only once). It is also interesting to note that by using &&, you make sure the second command is executed only if the first one succeeds (yet, I don't see how find could fail in your case). However, when using find only (-exec), the chmod command is called for each file matching the find criteria. If you have 200 files in your directory, chmod will be called 200 times, which is slower than calling chmod once, on 200 files. Of course, in the end, since chmod is a relatively quick and casual operation, you will not feel the difference on a reasonable number of files. Finally, another detail about passing file names between programs: spaces. According to how each commands processes file names (using proper quotes or not), you may run into trouble while processing files with spaces in their names (since This Super Picture.png could quickly be processed as This, Super and Picture.png).
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 *.nef to the command tar -czf {filename}.tgz {filename}.*, but I'm afraid I've no idea where to start. Thanks in advance.
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 |----- foo.jpg (860 KB) |----- baz.jpg (200 KB) I'd like to produce the output lines (order unimportant): bar.jpg dir/foo.jpg dir/baz.jpg How can I do this, preferably from bash?
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 '\0' '\n' If you want to remove the duplicates, with zsh: allfiles=(**/*(D.oL)) typeset -A best for f ($allfiles) best[$f:t]=$f bestfiles=($best) dups=(${allfiles:|bestfiles}) rm -rf -- $dups Description of some zsh features: typeset -A best: declares an associative array variable like in ksh93. Recent versions of bash support it as well. **/*: recursive globbing. Introduced by zsh in the early nineties, now found in in a few other shells with variations. (D.oL): globbing qualifiers. Another zsh invention, not copied yet by other shells though it's an essential companion to recursive globbing. Used to further qualify the glob. D to include dot files, . to only include regular files, oL to order by length (size in bytes). ${file:t}: like in (t)csh, expands to the tail part of a filename (the basename). ${a:|b} expands to the elements of a that are not in b. (a - b).
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 machine, something like root root 1150 Dec 30 12:11 file.txt.
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 /opt/apache../webapps/Context -type f -exec ls -l {} +" How it works ssh remotemachine command This executes command on remotemachine using secure-shell (ssh). command can be any command of your choosing. In the two examples above, I used: ls -l /opt/apache../webapps/Context This displays the directory listing of /opt/apache../webapps/Context in the "long" format. You may use any of ls's options to select the format or sorting that you prefer. See man ls. find /opt/apache../webapps/Context -type f -exec ls -l {} + This uses find to search recursively through subdirectories. The files it finds are again displayed with ls. -type f tells find to show only regular files and not directories. find has many options which you may use to select just the files that interest you. See man find. More Options If you want to save the output to a file, use redirection. For example: ssh remotemachine "ls -l /opt/apache../webapps/Context" >outputfile If you want both to display the output on the screen and also to save to a file, use tee: ssh remotemachine "ls -l /opt/apache../webapps/Context" | tee outputfile
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 "dir" in their home folder). I tried several possibilities, but could not get it working. Here is one of my tries: export TEST='$HOME/dir' We can check that the variable has indeed been created : env | grep TEST Which returns: TEST=$HOME/bin So far so good. However this is where things get tough : cd $TEST Returns: bash: cd: $HOME/bin: No such file or directory However following variant works: eval cd $TEST Is there any way to obtain the same result, but without invoking eval?
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 have at your disposal the eval shell built-in: % one=two ; two=three ; eval echo \$$one > three % eval "one=\$$two" ; echo $one > three It does not store a one -> two pointer, but rather it evaluates its arguments as a single shell statement. If that's a little unclear to you, you're not alone. It basically means that the shell runs the same line twice, or at least as near as I can figure it does, and all of the second pass's assignments are affected by the first pass's expansions - which is not normally the case, as you demonstrate in your question. It also means that two's literal value from a certain point in time is stored in one - copied, not linked, so: % one=two ; two=three % eval echo \$$one ; two=four ; eval echo \$$one > three > three % echo $two > four But what's up with the backslash? Well, this is where it gets confusing - because you're making two passes you have to quote your quotes. The first pass expands $one to two and strips the first level of quotes, so bye-bye \backslash, but the quoted dollar-sign remains and so $two becomes three on the second pass. This gets really crazy really fast. Shell quotes are hard enough to deal with as it is - just try to quote a single quote. Layer them and you're asking for trouble, strip, evaluate, strip, evaluate and you're going nowhere safe at all - because quotes are there to protect the values of shell parameters and environment variables and the shell from their values. So what you've done is store a literal $ dollar sign within the value of your variable. You didn't store a path to $HOME because the shell did not expand its value during assignment - again, by design. % dir=some_dir ; eval "$dir=\$HOME" ; echo $some_dir > /your/$HOME/path/ You don't have to ask around much about this stuff before you hear of the evil eval. It's commonly called that, and for good reason. Look: two=var\ \;rm\ -f\ /all/your/stuff ; eval home=$two Above home is assigned to the expansion of $two. The home= portion of the statement is evaluated twice - after the first pass and before the second, home briefly equals "$two" ; but upon the second, after the quotes are stripped, $home expands to var and /all/your/stuff equals 0. That's a super basic quoting example as well, it can go really wrong in a more complicated situation - and just requirement of eval tends to denote complicated. There are other ways to accomplish this - GNOUC notes the ${!bash specific} value inversion assignment (I think that's what it's called...) which probably just does the same thing but in a way that bash has attempted to safeguard. That's a good thing. You could also - and this is probably a good idea - write a function to spit out the values you want when it's called: _home() { exec 2>/dev/null ; set -- /home/*/ ; for h do ( cd "$h" && cd "$dir" && printf %s\\n "$dir" ) done } ; var="$(_home)" ; echo "$var" > probably... > the... > result... > you... > wanted... Almost as dangerous as eval can be a little imagination in combination with use of the shell's . as well. Because .'s job is to execute commands in the current shell environment rather than subshelling out as do pipes and etc, it's possible to construct a twice-evaluated statement that can affect your environment variables with little fuss. For instance, if you do not quote the limiter on a here-document its contents are subject to shell expansion. If you take that one further and . source it you can execute the results of its expansions. Like this: % . <<HERE /dev/stdin > ${one=two}three=four > home='$HOME' > HERE % [ "$home" = "$HOME" ] && echo $twothree > four See, in this way, at least, the quotes are easier because they're not stripped except from within an expansion, but they can still get tricky when your expansions do contain quotes. Anyway, that about wraps it up for what I know on the subject. Actually, one more thing, and this is super-duper risky, but it's your computer: % var=eval\ echo\ \$HOME % $var > /YOUR/HOME But... % cd eval echo $HOME obviously doesn't work...
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: find . -d -type f -execdir rename -n -X ${=CHARACTER_SUBSTITUTIONS} {} + I get the correct list of files in my test folder: 'untitled file3 [].txt' would be renamed to 'untitled file3 --.txt' 'untitled file2. [].txt' would be renamed to 'untitled file2. --.txt' But when I run it for realsies, it can't find them anymore: find . -d -type f -execdir rename -X ${=CHARACTER_SUBSTITUTIONS} {} + Result: Can't rename 'untitled file3 [].txt' to 'untitled file3 --.txt': No such file or directory Can't rename 'untitled file2. [].txt' to 'untitled file2. --.txt': No such file or directory Banging my head against a wall. Any help would be greatly appreciated. In case it's relevant, CHARACTER_SUBSTITUTIONS is just a long list of the subs I want to make. echo ${=CHARACTER_SUBSTITUTIONS} -S [ - -S ] - -S + - -S # - -S % - -S { - -S } - -S \ - -S < - -S > - -S * - -S ? - -S $ - -S ! - -S : - -S @ - -S ` - -S | - -S ' - -S " - -S & - -S  - -S = - Details: zsh MacOS Big Sur rename v1.601 (one of the Perl-based variants)
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:]]/-}' # -v: verbose mv -- 'untitled file2 [].txt' 'untitled file2 --.txt' mv -- 'untitled file3 [].txt' 'untitled file3 --.txt' % [^. [:IDENT:]] matches anything that's not a dot, space or valid part of a shell identifier. (#q.) is to restrict the rename to regular files like your -type f. For more info: Parameter expansion Glob operators zmv
zsh find -execdir rename "no such file or directory"