我遇到了这样一种情况:我正在将compgen -G的输出输送到xargs basename,直到我添加了xargs -I参数,才能让它正常工作,如下所示。这是一个脚本,展示了我想要做的事情,并附有解释性的注释。我有两个问题,它们出现在剧本后面。
# create three files for testing:
touch /tmp/my.file.1.2.txt
touch /tmp/1.my.file.2.txt
touch /tmp/1.2.my.file.txt
# create a glob and verify that it works with compgen:
glob=/tmp/*.file*.txt
compgen -G "$glob"
#output:
/tmp/1.2.my.file.txt
/tmp/1.my.file.2.txt
/tmp/my.file.1.2.txt
# try to get the basename of each file using xargs.
# I thought this would work, but it does not.
compgen -G "$glob" | xargs basename
#output:
basename: extra operand ‘/tmp/my.file.1.2.txt’
Try 'basename --help' for more information.
# eventually I discovered that this would work.
# however, I don't understand why this would work
# but the previous attempt would not, since I
# think that this command is just a more
# explicitly-specified version of the previous
# one.
compgen -G "$glob" | xargs -I{} basename {}
#output:
1.2.my.file.txt
1.my.file.2.txt
my.file.1.2.txt其他命令使用不带xargs参数的-I。例如,compgen -G "$glob" | xargs ls -al工作得很好。
问题1:这个脚本中的basename需要-I参数是什么?
问题2:在观察到这个结果之前,我认为xargs basename和xargs -I{} basename {}是彼此的同义词,但显然不是。有什么关系?
我怀疑这是否重要,但以防万一:这发生在运行在Ubuntu20.04.4(5.13.0-35-泛型)上的bash5.0.17(1)-release上。
我知道还有其他方法来生成这个文件列表,但我很担心,因为我显然没有理解一些我需要理解的基本内容,以避免将来出现错误。
发布于 2022-03-21 15:14:42
POSIXbasename一次只处理一个名称,也可以选择删除后缀。xargs basename尝试使用尽可能多的参数一次运行basename,这失败了;xargs -I{} basename {}导致xargs在每个名称下运行basename一次来处理。
的输出比较
printf "foo\nbar\nbaz" | xargs echo basename和
printf "foo\nbar\nbaz" | xargs -I{} echo basename {}GNU basename支持两种允许多个名称的选项;如果不需要指定后缀:
xargs basename -a如果你这么做了
xargs basename -s .suffixhttps://unix.stackexchange.com/questions/696271
复制相似问题