我在名称的末尾有一些带空格的文件或目录。 shell可以删除吗?
由于
答案 0 :(得分:3)
for f in *[[:space:]]; do # iterate over filenames ending in whitespace
[[ -e $f || -L $f ]] || continue # ignore nonexistent results (ie. empty glob)
d=$f # initialize destination variable
while [[ $d = *[[:space:]] ]]; do # as long as dest variable ends in whitespace
d=${d:0:((${#d} - 1))} # ...trim the last character from it.
done
printf 'Renaming %q to %q\n' "$f" "$d" >&2 # log what we're going to do
mv -- "$f" "$d" # and do it.
done
请参阅:
${varname:start:length}
从位置start
开始获取给定长度的切片。)for
loop,用于迭代glob结果。 printf %q
说明符是一个bash扩展,它以一种方式将字符串格式化为eval
回原始字符串的内容 - 因此,它可以打印一个以空格结尾的名称name\
或'name '
,但会以某种方式确保读者可以看到空格。
答案 1 :(得分:0)
这是一个没有外部调用的本机POSIX shell解决方案。
#!/bin/sh
for file in *[[:space:]]; do # loop over files/dirs ending in space(s)
[ -e "$file" ] || continue # skip empty results (no-op)
new_file="${file%[[:space:]]}" # save w/out first trailing space char
while [ "$file" != "$new_file" ]; do # while the last truncation does nothing
file="${file%[[:space:]]}" # truncate one more trailing space char
done
# rename, state the action (-v), prompt before overwriting files (-i)
mv -vi -- "$file" "$new_file"
done