查找-exec与sed一起使用时,文件重命名不起作用

时间:2017-10-19 06:55:28

标签: bash unix sed terminal zsh

我一直在尝试:

find dev-other -name '*.flac' -type f -exec echo $(echo {} | sed 's,^[^/]*/,,') \;

我希望在.flac中看到dev-other个文件的路径列表,但没有前置dev-other/,例如:

4515/11057/4515-11057-0095.flac
4515/11057/4515-11057-0083.flac
4515/11057/4515-11057-0040.flac
4515/11057/4515-11057-0105.flac
4515/11057/4515-11057-0017.flac
4515/11057/4515-11057-0001.flac

相反,我看到了

dev-other/4515/11057/4515-11057-0095.flac
dev-other/4515/11057/4515-11057-0083.flac
dev-other/4515/11057/4515-11057-0040.flac
dev-other/4515/11057/4515-11057-0105.flac
dev-other/4515/11057/4515-11057-0017.flac

为什么sed取代在这里工作,即使它可以独立工作

$ echo $(echo dev-other/4515/11057/4515-11057-0047.flac | sed 's,^[^/]*/,,')
4515/11057/4515-11057-0047.flac

我首先尝试扩展:

find dev-other -name '*.flac' -type f -exec a={} echo ${a#*/} \;

但得到了错误:

find: a=dev-other/700/122866/700-122866-0001.flac: No such file or directory
find: a=dev-other/700/122866/700-122866-0030.flac: No such file or directory
find: a=dev-other/700/122866/700-122866-0026.flac: No such file or directory
find: a=dev-other/700/122866/700-122866-0006.flac: No such file or directory
find: a=dev-other/700/122866/700-122866-0010.flac: No such file or directory

1 个答案:

答案 0 :(得分:0)

使用带有find选项的-exec

时,您可以使用参数展开作为用例
find dev-other -name '*.flac' -type f -exec bash -c 'x=$1; y="${x#*/}"; echo "$y"' bash {} \;

我使用bash使用单独的shell(使用shbash -c)因为涉及涉及参数扩展的单独字符串操作。可以将find结果的每个输出视为作为参数传递给此子操作的子shell。

bash -c执行命令时,命令后面的下一个参数用作$0(脚本在进程列表中的“名称”),后续参数成为位置参数({{1 },$1等)。这意味着find传递的文件名(代替$2)成为脚本{}的第一个参数,并由迷你脚本中的--引用

如果您不想使用额外的$1,请使用bash就地

_

其中find dev-other -name '*.flac' -type f -exec bash -c 'x=$1; y="${x#*/}"; echo "$y"' _ {} \; i是_预定义变量(例如,未在bash中定义):“在shell启动时,设置为用于调用shell的绝对路径名或shell脚本在环境或参数列表中传递时执行“(参见man bash - Special Parameters部分)

值得看Using Find - Complex Actions