问题
I want to iterate through a list of files without caring about what characters the filenames might contain, so I use a list delimited by null characters. The code will explain things better.
# Set IFS to the null character to hopefully change the for..in
# delimiter from the space character (sadly does not appear to work).
IFS=$'\0'
# Get null delimited list of files
filelist="`find /some/path -type f -print0`"
# Iterate through list of files
for file in $filelist ; do
# Arbitrary operations on $file here
done
The following code works when reading from a file, but I need to read from a variable containing text.
while read -d $'\0' line ; do
# Code here
done < /path/to/inputfile
回答1:
In bash you can use a here-string
while IFS= read -r -d '' line ; do
# Code here
done <<<"$var"
Note that you should inline the IFS=
and just use -d ''
but make sure there is a space between the 'd' and the first single-quote. Also, add the -r
flag to ignore escapes.
Also, this isn't part of your question but might I suggest a better way to do your script when using find
; it uses process substitution.
while IFS= read -r -d '' file; do
# Arbitrary operations on "$file" here
done < <(find /some/path -type f -print0)
回答2:
I tried working with the bash examples above, and finally gave up, and used Python, which worked the first time. For me it turned out the problem was simpler outside the shell. I know this is possibly off topic of a bash solution, but I'm posting it here anyway in case others want an alternative.
import sh
import path
files = path.Path(".").files()
for x in files:
sh.cp("--reflink=always", x, "UUU00::%s"%(x.basename(),))
sh.cp("--reflink=always", x, "UUU01::%s"%(x.basename(),))
来源:https://stackoverflow.com/questions/8677546/reading-null-delimited-strings-through-a-bash-loop