重命名多个文件,更改扩展名和字符串的一部分

时间:2017-12-22 06:19:20

标签: bash shell xargs

我在目录中有*.new个文件列表。这些文件的名称中包含D1,要替换为D2,并且还必须将.new中的扩展名删除

hello_world_D1_122.txt.new -------> hello_world_D2_122.txt

我尝试的是

ls -slt | grep -iE "*.new$" | awk -F " " '{print $10}' | xargs -I {} mv {} "echo {} | sed -e 's/.D1./.D2./g ; s/.new//g'"

此命令未产生所需的输出。输出上述命令是

mv: rename hello_world_D1_122.txt.new to echo hello_world_D1_122.txt.new | sed -e 's/D1/D2/g ; s/.new//g': No such file or directory

3 个答案:

答案 0 :(得分:4)

为什么所有关于使用大量shell工具的方法,你可以使用bash工具内置函数,使用参数扩展语法进行字符串操作

for file in *.new; do 
    [ -f "$file" ] || continue
    temp="${file%*.new}"
    mv -- "${file}" "${temp/D1/D2}"
done

文件名中"${file%*.new}"部分的.new"${temp/D1/D2}"D1替换为D2

我不知道为什么持久化使用GNU xargs,但你可以使用这种不可读的方式来实现这一点。使用printf列出具有null分隔符的文件,并使用xargs -0读取null作为分隔符,

printf '%s\0' *.new | xargs -0 -r -I {} sh -c 'temp="${0%*.new}"; mv -- "${0}" "${temp/D1/D2}"' {}

答案 1 :(得分:1)

除了明显的语法错误外,您当前的尝试还包含大量问题。

参数"echo {} | sed '...'"是一个文字字符串; xargs无法将此解释为命令(尽管它当然会用此字符串中的文件名替换{}。)

此外,don't use ls in scripts如果你真的需要,使用ls -l然后丢弃长格式......只是愚蠢,低效,容易出错(参见链接详情)。

解决此问题的明显而优越的方法是没有xargs

for f in ./*.new; do
    [ -f "$f" ] || continue   # in case the glob matches no files
    d=${f%.new}               # trim off extension
    mv "$f" "${d/.D1./.D2.}"  # replace .D1. with .D2.
done

(我想你想要替换字面点,尽管你的正则表达式会匹配任何字符,除了换行符后跟D1后跟除换行符之后的任何字符。)

如果您坚持使用xargs解决方案,则可以将上述脚本包含在bash -c '...'中并将其传递给xargs

printf '%s\0' ./*.new | xargs -r0 bash -c 'for f; do d=${f%.new}; mv "$f" "${d/.D1./.D2.}"; done' _

答案 2 :(得分:1)

使用GNU Paralllel看起来像这样:

parallel mv {} '{=s/D1/D2/;s/.new//=}' ::: *.new

如果你有疯狂的文件名:

touch "$(printf "Shell  Special\n\n'*$!_D1_txt.new")"
parallel -0 mv {} '{=s/D1/D2/;s/.new//=}' ::: *.new
相关问题