对我来说,所有内置的工具都有点麻烦(我是否正确使用了shell引用?它是否会做正确的事情?我能轻松预览更改吗?)。
几年前,我编写了 rpt,它将接受其命令行参数,打开文本编辑器(让您编辑文件名),然后运行一个命令(默认为mv
)在旧文件名和新文件名上。
最近,我又进一步发展了这个工具,这就是 fea
(对于每个参数):
import sys, shlex, re
_, cmd, *args = sys.argv
print('\n'.join(re.sub(r'[{](.)([^}]*?)(\1)([^}]*?)(\1)[}]',
lambda m: shlex.quote(re.sub(m.group(2), m.group(4), arg)),
cmd).replace('{}', shlex.quote(arg)) for arg in args))
以下替换发生:
{} -> insert arg
{/regex/replacement/} -> run re.sub(regex, replacement) on the arg,
you can pick any character for "/", as long
as it appears at the start, middle and end
(to separate the regex from the replacement)
一些用例:
# Create backup files
fea "cp {} {}.bak" *.py
# Encode WAV files with oggenc
fea "oggenc {} -o {/wav$/ogg/}" *.wav
# Decode MP3 files with mpg123
fea "mpg123 -w {/mp3$/wav/} {}" *.mp3
# Render markdown documents to HTML
fea "markdown {} > {/md$/html/}" *.md
# Fancy replacement
fea "markdown {} > {#input/(.*).md#output/\1.html#}" input/*.md
# As mentioned above, note that you need to pipe the
# fea output into a shell to execute the command
fea "cp {} {}.bak" *.py | sh -e -x
您的用例可以这样描述:
:
find . -name '*.in' -print0 | xargs -0 fea "python somescript.py {} {/in$/out/}"
或者,如果文件只存在于当前文件夹中:
fea "python somescript.py {} {/in$/out/}" *.in
如果你正在使用 zsh
并且需要 递归通配符:
fea "python somescript.py {} {/in$/out/}" **/*.in
如果你对显示的命令感到满意,只需将其输出导入到
sh -e -x
(或
bash
或其他)中执行。
虽然使用shell(或任何参数/变量扩展)可以创建
for
循环,但是对于我来说,shell引用和转义非常难以正确处理,
fea
工具确保它也适用于奇怪的名称。
touch 'some$weird "filename.py'
touch 'and !! more.py'
touch 'why oh why?.py'
touch "this is ridiculous'.py"
fea "cp {} {}.bak" *.py | sh -e -x
请参阅
rpt and fea博客文章以获取详细信息。