简体   繁体   中英

Folder name with Parentheses in bash variable

So, I have parentheses in folder name with spaces:

folder\\folder (2000)\\file.srt

folder\\folder (1990)\\file.srt

for file in `find . -name "*.srt"`
do
 echo "file = $file";
done

Don't work in my script. Anyone can help-me?

You could use find -exec for this:

find . -name "*.srt" -exec echo "file = {}" \;

Output:

file = ./folder/folder (1990)/file.srt
file = ./folder/folder (2000)/file.srt

The problem is that the spaces in the filenames produced by find(1) are getting interspersed into the names separated by \\n s, and the for command gets them all without differencing them.

The best approach (and one that saves commands) is to use find(1) with the -print0 option, that prints the filenames separated by a null character, and then use the xargs command with the -0 option, which expects nulls as separators. This way you can execute a command with as much parameters as the system can afford. For example

find . -type f -name "* *" -print0 | xargs -0 cat

will print the contents of all files that have a space in their name.

In your example, you want to do some scripting with each data line, so a better approach will be to use the read shell command, as in (in this case, you don't need the -print0 option, as the files are delimited by newlines, so you'll read a file per read)

find . -name "*.srt" | while read file
do
    echo "file = ${file}"
done

but in this case you'll not get the efficient xargs(1) use, putting as many parameters in the command line of the called command as possible. You'll process each file one file at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM