我希望从包含单引号文件名的文本文件中处理文件,如
'new'$'\n''line'
'tab'$'\t''ulator'复制和粘贴用于手动处理这些文件工作得很好:
test -f 'tab'$'\t''ulator'现在,使用bash builtin命令读取文件。
while IFS="" read -r myfile; do
line=$myfile
...
done < text.txt提供包含转义单引号的字符串,如
'\''new'\''$'\''\n'\'''\''line'\'''
'\''tab'\''$'\''\t'\'''\''ulator'\'''但是,在bash脚本中处理这个文件名不起作用。
test -f "$myfile"
test -f ${myfile}如何在bash中禁用/undo转义单引号和处理原始文件名?
发布于 2016-07-19 21:42:13
使用eval
许多人相当合理地认为 as a mis-spelling of evil。因此,我认为这个解决方案是最后的选择,只有当所有其他方案都失败时才使用。
让我们拿出这个示例文件:
$ cat badformat
'new'$'\n''line'
'tab'$'\t''ulator'我们可以读取和解释这些文件名,如下例所示:
while read -r f; do
eval "f=$f"; [ -f "$f" ] || echo "file not found"
done <badformat使用NUL分隔的文件名列表
惟一不能出现在Unix文件名中的字符是NUL (十六进制00)。因此,许多Unix工具被设计成能够处理NUL分隔的列表。
因此,在创建文件时,替换:
stat -c %N * >badformat通过以下方式:
printf '%s\0' * >safeformat后一个文件可以通过while-read循环读取到shell脚本中。例如:
while IFS= read -r -d $'\0' f; do
[ -f "$f" ] || echo "file not found"
done <safeformat除了shell边读循环之外,请注意,grep、find、sort、xargs以及GNU sed和GNU awk都具有处理核分隔列表的本机能力。因此,NUL分隔列表方法既安全又支持良好。
发布于 2016-07-19 21:32:50
通过字符串操作找到解决方案
${filename//$'\047'\\$'\047'$'\047'/$'\047'}正如您前面提到的,对于像rm这样的文件名,使用eval是非常危险的。对于stat -c %N (它只转义单引号、行提要和制表符)还有另一种解决方案
while IFS="" read -r myfile; do
filename="$myfile"
filename="${filename#?}"
filename="${filename%?}"
filename="${filename//"'$'\t''"/$'\011'}"
filename="${filename//"'$'\n''"/$'\012'}"
filename="${filename//$'\047'\\$'\047'$'\047'/$'\047'}"
test -f "$filename" && echo "$myfile exists"
done < text.txthttps://stackoverflow.com/questions/38467862
复制相似问题