58

我想遍历文件列表而不关心文件名可能包含哪些字符,因此我使用由空字符分隔的列表。该代码将更好地解释事情。

# 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

以下代码在从文件中读取时有效,但我需要从包含文本的变量中读取。

while read -d $'\0' line ; do
    # Code here
done < /path/to/inputfile
4

5 回答 5

102

执行此操作的首选方法是使用进程替换

while IFS= read -r -d $'\0' file; do
    # Arbitrary operations on "$file" here
done < <(find /some/path -type f -print0)

如果您一心想以类似的方式解析 bash 变量,只要列表不是NUL 终止的,您就可以这样做。

这是一个 bash var 保存制表符分隔字符串的示例

$ var=$(echo -ne "foo\tbar\tbaz\t"); 
$ while IFS= read -r -d $'\t' line ; do \
    echo "#$line#"; \
  done <<<"$var"
#foo#
#bar#
#baz#
于 2011-12-30T08:25:15.567 回答
1

用于env -0按零字节输出分配。

env -0 | while IFS='' read -d '' line ; do
    var=${line%%=*}
    value=${line#*=}
    echo "Variable '$var' has the value '$value'"
done
于 2021-09-20T21:10:27.693 回答
1

管道它们xargs -0

files="$( find ./ -iname 'file*' -print0 | xargs -0 )"

xargs 手册

-0, --null
    Input items are terminated by a null character instead of
    by whitespace, and the quotes and backslash are not
    special (every character is taken literally).
于 2021-09-29T11:19:15.703 回答
-1

就可读性和可维护性而言,bash 函数可能更简洁:

MOV将文件转换为MP4using的示例ffmpeg(适用于包含空格和特殊字符的文件):

#!/usr/bin/env bash

do_convert () { 
  new_file="${1/.mov/.mp4}"
  ffmpeg -i "$1" "$new_file" && rm "$1" 
}

export -f do_convert  # needed to make the function visible inside xargs

find . -iname '*.mov' -print0 | xargs -0 -I {} bash -c 'do_convert "{}"' _ {}

于 2021-11-16T12:43:44.107 回答
-5

我尝试使用上面的 bash 示例,最后放弃了,并使用了第一次工作的 Python。对我来说,事实证明问题在外壳之外更简单。我知道这可能是 bash 解决方案的主题,但无论如何我都会在这里发布它,以防其他人想要替代方案。

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(),))
于 2018-04-13T14:09:07.787 回答