Showing posts with label find. Show all posts
Showing posts with label find. Show all posts

Friday, December 27, 2019

Trim characters from the end of all directory names in a folder

On my windows system, I had a folder with only other folders in it, and all of them had three characters on the ends of their names that I wanted to delete. I started up a Cygwin Bash shell to do the job.

I first attempted to use 'find' to create a one line command to rename all of these folders, but it turns out bash for and do were the answer, thusly:
for file in *; do mv "$file" "${file%???}"; done

The syntax for doing the trimming came from this thread (although sadly the pythonesqe method of trimming with colons and a negative end position didn't work in cygwin bash for some reason): https://stackoverflow.com/questions/19530429/rename-file-by-removing-last-n-characters
The example of using for/do came from here: https://stackoverflow.com/questions/7450818/rename-all-files-in-directory-from-filename-h-to-filename-half

Friday, April 12, 2019

Add folder name to file name linux

I had a bunch of misnamed files throughout a directory tree that I had to fix the names of to have a common prefix with the name of their folder appended. Actually it was the name of a folder two levels up.

Theoretically a single-line 'find' command with the right -exec should be possible. However, encapsulating an awk script within a mv command hanging off of find, even with xargs proved to be too tricky, and I ended up just creating an echo statement with the mv commands and then taking the echoed output and putting it into a shell script.

Here is the final find-xargs-awk command line which generated the stdout that I pasted into my shell script. In this case, the original files are in ./$TL/$SL/ and $TL is a date code and I wanted to find the oldfile which had the wrong date code on the front and rename it to a new file prefix with the desired datecode on the end:
find . -name "*oldfile.csv" | xargs -I '{}' echo {} | awk -F'/' '{SL = NF-1; TL = NF-2; print "mv " $FILENAME "./" $TL "/" $SL "/newfile_" $TL ".csv"}'

Here are some relevant links turned up during researching this:

Here's a super simple example of using find to rename files. The commenter here likes xargs too much when it's unnecessary: https://unix.stackexchange.com/questions/227662/how-to-rename-multiple-files-using-find
I tried using SED to split up the directory path but it's way too hard to get it to treat slashes as delimiters, plus the result keeps the delimiter for some reason: https://stackoverflow.com/questions/16643288/sed-to-extract-text-between-two-strings
Still trying to get sed to work, here is a nice comparison of the same task with parentheses in different languages: https://unix.stackexchange.com/questions/108250/print-the-string-between-two-parentheses
Here is an example that is a lot of what I needed with my two directory levels, but aside from generally reminding me how to use awk I didn't end up stealing a lot of this: https://unix.stackexchange.com/questions/277231/how-to-get-second-directory-name-in-the-perforce-file-path
Here is the example that I stole most of my awk code from. It has several great examples, including using a for loop (which turned out to be largely unnecessary for me) and the kint of using the built-in swk variable FILENAME. https://unix.stackexchange.com/questions/134212/extract-file-name-from-path-in-awk-program
Here is where I got the other part of my awk code using the NF built in variable. The example is in a for loop but I was able to do the same thing with find and xargs: https://stackoverflow.com/questions/643372/append-name-of-parent-folders-and-subfolders-to-the-names-of-the-multiple-files
Here is an example of a super fancy xargs command with find: https://stackoverflow.com/questions/10972002/batch-renaming-files-in-command-line-and-xargs
Here is an example where somebody was just not doing xargs correctly, and the answers eventually converge on just using the -exec feature of find: https://unix.stackexchange.com/questions/90886/how-can-i-find-files-and-then-use-xargs-to-move-them
Here is another example of a for loop for somebody that is trying to do something remarkably similar to what I want to do, but these examples weren't actually very helpful: https://superuser.com/questions/516082/add-folder-name-to-beginning-of-filename



Friday, April 5, 2019

Copy files using find, dirname

I wanted to find files that existed in several but not all branches of a directory tree and make a copy of each file within its directory to a new (constant) filename.

The key was in using the magical -execdir option to find rather than just -exec.

Info on dirname and basename: https://stackoverflow.com/questions/2536046/extract-directory-path-and-filename

This StackExchange answer provided the key information which is that dirname wasn't going to help me because it is evaluated before find! Also the backwards quotes for using the evaluation of a command inside a command line. https://unix.stackexchange.com/questions/339880/cp-not-evaluating-dirname-properly-in-find-operation?rq=1

Here are some harder ways to do it with xargs: https://stackoverflow.com/questions/17368872/how-to-move-or-copy-files-listed-by-find-command-in-unix

My final command line:
find . -name "Prefix*.txt" -execdir cp -p `basename {}` newfilename.txt \;

Wednesday, March 20, 2019

Find files, list contents with line length maxium

I needed to parse a directory tree and list all the files of a particular type, list the directory name, print the first few lines of each file, with long line lengths trimmed. I also wanted to only get the particular types of lines out of that initial listing, which are ones with the date in the first few characters.

Here is my massive final command:
find . -name "*.csv" -exec echo {} \; -exec head -n 21 {} \; | cut -c -70 | grep 2018 | grep -v DATE | grep -v UTEND

The beautiful parts of this were: 1) two -exec functions for my find command. Yep you can do that. 2) The cut command 3) a chain of greps to get the date and cut out other lines that had the date that I didn't want.

Friday, May 9, 2014

Converting a directory listing into a shell script of copy commands

I needed to copy all the files of a certain name throughout a directory tree into a particular directory, renaming them to contain the name of the path where they had been found so that they could be restored from the copy if needed later.

Trying to be quick about it, I decided to just pipe the result of "find" into a file, and then use a stream editor to modify the file into a shell script that would do the copy.

find . -name "filename.txt" > ~/filelist.txt

After fiddling with sed as an option for changing each line of the file into a copy command, I eventually found awk to be easier to use for this purpose (gawk on all our Linux systems).

gawk '{{ORS=""};print "cp -v " $0;gsub(/\//,"+",$0);{ORS="\n"};print " ./files_backup/" $0}' ~/filelist.txt > ~/files_backup.sh

So this reads filelist.txt which is a list of all found instances of filename.txt with full paths, creates a cp -v command with the original path as the first argument and a second argument with a destination directory of files_backup and a destination filename consisting of the first argument with all "/" characters replaced with +; the result is output to files_backup.sh which is the shell script that will actually do the copying for me. I didn't want to waste more time getting fancy by trying to directly execute the command, plus this gives me a chance to check the result before running it. The "+" character was chosen for the destination filenames because some of the directories in the source paths already had underscores and dashes in their names, and it appears as though the + is an allowable filename character.

I was bedeviled by awk's default behavior of inserting \n to the results of each print statement; I knew that I'd overcome this in the past but for today my Google search yielded a workaround of changing the end of line character to nothing for the first print statement (I had to change it back for the second print statement in order to get the completed line with a \n at the end.

Some links:

A typical sed replacement example forum thread:
http://www.unix.com/shell-programming-and-scripting/12657-using-sed-replace-part-string.html

A fascinating diversion into bash for loops. At one point I tried using a for loop to generate copy commands "live" from the file list but it didn't work because the list that for uses seems to need to be an actual directory listing rather than lines from a file.
http://www.cyberciti.biz/faq/bash-for-loop/

Here's a bunch of different approaches to a similar (although simpler) task. This thread has examples of using sed, a for loop, and the "rename" command which I hadn't heard about before as possible solutions.
http://unix.stackexchange.com/questions/7161/copy-rename-multiple-files-using-regular-expression-shell-script

A link with basic awk syntax:
http://www.grymoire.com/Unix/Awk.html

Another page of basic awk syntax that shows the syntax for the gsub command and an example:
http://www.staff.science.uu.nl/~oostr102/docs/nawk/nawk_92.html

Another page of basic awk syntax, for print statments.
http://www.thegeekstuff.com/2010/01/awk-introduction-tutorial-7-awk-print-examples/

Here's a basic question that I keep forgetting the answer to with awk, how to control whether concatenated outputs are padded with white space or not; the answer is really quite simple!
http://stackoverflow.com/questions/9985330/how-can-i-get-awk-to-print-without-white-space

I was attempting to copy the input argument to a new variable and modify the new variable the first time I tried to do this, but for some reason the modifications that I was making to the new variable affected the input variable also. I didn't have time to figure out why this was happening, and thus had to reorder my awk statment such that I printed the input argument before modifying it, which is what led to having to fiddle with ORS. Perhaps something in this page of examples, which I was trying to follow but somehow failed, explains why I was having this problem:
http://www.thegeekstuff.com/2010/01/awk-tutorial-understand-awk-variables-with-3-practical-examples/

Here's where I got the solution to directly change ORS from:
http://stackoverflow.com/questions/2021982/awk-without-printing-newline

Here's the information on what are the allowed filename characters in *nix (and other OSs too):
http://en.wikipedia.org/wiki/Filename



Tuesday, April 22, 2014

Linux removing all directories of a certain name from a directory tree

Ok, so it's actually a Unix system.

I had to removed all directories of a certain name from a directory tree. No biggie, just using find here, along with du to tell me how big these bad things were on the file system:

find . -name "[directory name] -exec du --si {} \;"

Note that du -k gave it in kilobytes, and -m gave it in megabytes, and there is no -g option. However --si just picks the best units to show for each line output.

My thought was that I could use -exec rm -r {}\; with this find statment to delete the directories. However, the non grata directories appeared at different levels, sometimes within each other. This listing gave the top directories first, which meant after I had deleted the top directory find might still return the lower directory if the transfer of lines to -exec is done after find is completed. The solution was to use the argument to reverse the lower and higher level results:

find . -d -name "[directory name] -exec rm -r {} \;"

The downside to this is I was getting pestered my messages that said "find: warning: the -d option is deprecated; please use -depth instead, because the latter is a POSIX-compliant feature.". I didn't have time to figure out if -depth really is a drop-in replacement for -d.

Friday, February 22, 2013

Extracting one value from logged ascii packet data

Here is my personal trending tool for work, producing three columns space delimited file that can be imported into Excel

find . -name "*.log" -exec grep Keyword -H {} \; | sed -e 's/: 10/:10/' | awk '{print $1 " " $2 " " $68}' | sed -e 's/.l
og:2/.log: 2/' > ~/output.txt

Thursday, February 21, 2013

Using gnuwin32 find and grep

My issue is that I've just been too lazy to set up my $PATH correctly on my windows system, so I have to call out the full executable path thusly:

"C:\Program Files\GnuWin32\bin\find" . -name "filename.txt" -exec "C:\Program Files\GnuWin32\bin\grep" -H Keyword {} ;

Thursday, January 31, 2013

unix copy file and create directory if it doesn't exist

My goal was to re-create a directory tree of files under a new root by copying them, creating all the same directory levels. I found a convoluted command line for doing this using xargs and split and stuff, but it turns out that cp has the most wonderful argument, --parents. Here was the solution:

find . -name "regex" -exec cp -p --parents {} /newroot \;

Saturday, November 10, 2012

sed insert lines before/after pattern match

Yet another wicked cool sed trick that I accomplished recently after a pile of googling. I needed to add a couple of lines of code into several files that all had great markers already in the code where I needed the new lines. I just had to do a pattern match on the marker phrases, and add the lines either before or after as needed. Looked like a job for sed (although some pointed out in the forum threads that I googled that awk would work probably easier). Anyhow, here's what I did to add a line after:

find . -name "prefix*.c" -exec sed -e '/pattern1/G;a\{new line1' -e'}' {} \;

I got the "G" part from examples and never did verify its offical capabilities, but that's what adds an extra blank line (from man, it seems to be appending the swap line to the current line?). The two -e arguments are the key to overcoming the difficulties with the "a" command.

In the spots where I wanted to add the line before a particular line, I didn't have time to figure out how to make a single command that would add the extra line plus a blank line, so I just wimped out and used two commands. The "x;p;x" bit is from another example in the single-liner file:

find . -name "prefix*.c" -exec sed -e '/pattern2/i\{new line2' -e'}' {} \;
find . -name "prefix*.c" -exec sed -e '/pattern2/{x;p;x;}' {} \;

Saturday, October 6, 2012

The incredible batch call of wkhtmltopdf

Like extra credit, this command line combined nearly everything I've done recently all at once. Within cygwin, I'm using find on a directory with the -exec option, and calling wkhtmltopdf on every file found. The only clunky thing about this method is that it makes .htm.pdf files which I have to rename to .pdf.

find . -name "D*.htm" -exec cmd /C "C:\Program Files\wkhtmltopdf\wkhtmltopdf.exe" -s Letter {} {}.pdf \;

The awesome trick was doing this in cygwin. For some reason, wkhtmltopdf wasn't running in cygwin naitive mode (it is a GnuWin utility in the form that I have it in), so I found from the below blog how to use cmd /C and I stuck the whole thing into the -exec of find and it somehow worked.

Yes, well, the downside is that I have to trim an extra .htm out of the pdf filename, I suppose that a real unix master would run the result of find through something else to trim the orignal suffix off before passing it into cmd /C, I should figure that out some day.

http://siddesh-bg.blogspot.com/2012/07/how-to-run-dos-commands-from-cygwin.html

Sunday, July 8, 2012

Renaming large groups of files with find

My normal inclination is to use xargs coupled with find to do something batch-y like renaming groups of files across a whole directory tree, but I've had a lot of trouble getting the syntax perfect for using something like cp with xargs. It turns out that the find at the start of the chain has a -exec argument that allows multiple uses of the found file name no fuss no muss like xargs should. The command is:

find . -name "*.htm" -exec cp -p {} {}.original \;

The key seems to be in the \; at the end, which I guess that I wasn't doing right before.

Here the site that had the info that got me this breakthrough; it's in somebody's comments near the bottom:

http://csm.mech.utah.edu/content/2011/03/01/use-of-the-shell-xargs-command/

Sunday, August 7, 2011

Batch text replace (using grep and sed to replace all occurances of a string in all files recursively through directories)

Easy enough, just grep for the string, and pass the returned file list into sed using xargs. But what about the details?

This site was my best hit on google using the obvious search:

http://stackoverflow.com/questions/1169927/using-sed-and-grep-to-search-and-replace

I used a slighly different set of arguments when I did it, since egrep seems like a royal pain for my purposes. I added a -t to my xargs call so I could monitor what it did each time it did it:

grep -l oldstring *.* | xargs -l -t sed -i -e 's/oldstring/NEWSTRING/g'

Here's a version using find that worked for me:

$ find . -name "*.htm" | xargs -l -t sed -i -e 's/oldstring/NEWSTRING/g'

Here's a novel way to just search for the files that have the string. Might be interesting to find a way to link this up with xargs for the substitution. Not sure what the extra backslash is about:

find . -exec grep -l “string to find” {} \;