bash - For loop using find lacks doesn't properly handle directory names having white space character -
OK I'm really stuck on this.
I have dirs.txt that is as follows:
/ var / tmp / old files.txt / var / tmp / old backups.bak< / Pre>The dirs.txt file is generated by the script
When I want to use dirs.txt in a loop for:
` Dirs.txt` for dir; Command throws: ls: can not use / var / tmp / old: no such file or directoryI want
Full filenames can be used by LS-L'Aid But it does try LS-L / var / tmp / old /
how can I fix it with a loop?
cat dirs.txt | While reading DIR; When you use a bactic operator, the output is divided into tokens on the character of each white spot. I ls -al "$ dir" done
The second On the side,
read, reads one line instead of one word at a time. So the solution, which looks odd, is in the loop in the loop so that it can be read by line.You need the quote
"$ Dir"in thelscommand to the full filename, the white location and all If you do not do this, thenlstwo filenames,/ var / tmp / oldandfiles.txt < / Code>.Maybe I'm going to honor you. You can
cat:It can make it even easier by eliminating what LS-L "$ dir" did & lt; Dirs.txtThis works because < Strong> Whole
while theloop acts like a large command, so you can also use file redirection in thecatlike a pipe.
Taking it even further ...
how
dirs.txtis generated, you can get rid of it completely You can do everything in one command and if it is just a temporary file, you can reduce it by piping and makedirs.txtin. Whereasloop directly, leaving a temporary file. For example, replace/ var -name '* old *' & gt; Dirs.txt while reading dir; Did LS-L "$ dir" & lt; Dirs.txtwith
find / var -name '* old *' | While reading DIR;lin-l "$ dir" done excuse
findwhatever order you make to create a file list.And in fact, if you are actually using
searchthen you might find a largeorderin the order without any end Or can do anything! For example, withsearchandwhilecan be done with a singlesearchcommand:Find / var-name '* Old *' -exec ls -al {} \;
searchis actually a flexible command that can detect files that match all kinds of complex criteria, and those files are called command line logic You can pass by using the other commands as-execoption when you use-execthen{}each file name Gets replaced with.
Comments
Post a Comment