简体   繁体   English

检查文件扩展名 BASH

[英]Check file extension BASH

I'm trying to compare 2 files that have the same name and the same contents but I only want to keep one of them.我正在尝试比较 2 个具有相同名称和相同内容的文件,但我只想保留其中一个。 Lets say I have the following假设我有以下内容

/root/dir1/file1.doc
/root/dir1/file1.pdf 

I only want to keep the .doc file what would be the best way to go about this?我只想保留 .doc 文件,最好的方法是什么?

From the dash manpage (and I believe all bash , ksh , and zsh "inherit" these features):dash联机帮助页(我相信所有bashkshzsh “继承”了这些功能):

${parameter%word} Remove Smallest Suffix Pattern. ${parameter%word} 删除最小后缀模式。 The word is expanded to produce a pattern.这个词被扩展以产生一个模式。 The parameter expansion then results in parameter, with the smallest portion of the suffix matched by the pattern deleted.参数扩展然后产生参数,后缀的最小部分与删除的模式匹配。

${parameter%%word} Remove Largest Suffix Pattern. ${parameter%%word} 删除最大后缀模式。 The word is expanded to produce a pattern.这个词被扩展以产生一个模式。 The parameter expansion then results in parameter, with the largest portion of the suffix matched by the pattern deleted.参数扩展然后导致参数,与删除的模式匹配的后缀的最大部分。

${parameter#word} Remove Smallest Prefix Pattern. ${parameter#word} 删除最小前缀模式。 The word is expanded to produce a pattern.这个词被扩展以产生一个模式。 The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted.参数扩展然后产生参数,其中与删除的模式匹配的前缀的最小部分。

${parameter##word} Remove Largest Prefix Pattern. ${parameter##word} 删除最大的前缀模式。 The word is expanded to produce a pattern.这个词被扩展以产生一个模式。 The parameter expansion then results in parameter, with the largest portion of the prefix matched by the pattern参数扩展然后产生参数,其中前缀的最大部分与模式匹配

In practice:在实践中:

shortSuff(){ printf '%s\n' "${1#*.}"; } 
#^applies the string op to the $1 positional parameter
#`printf '%s\n'` is like `echo` but doesn't break on e.g., hyphen-prefix arguments

file=/root/dir1/file1.doc
[ shortSuff "$file" = doc ] && echo "Yes, the short suffix is doc"

You can write a short script to do this for you:您可以编写一个简短的脚本来为您执行此操作:

#!/bin/bash
EXT="${1}"
if -z "${EXT}"; then EXT=".doc"; fi
TD="$(mktemp -d)"
mv ./*"${EXT}" "${TD}"
rm ./*
mv "${TD}"/* .
rmdir "${TD}"

Assuming your script is called keep_copy.sh , you would call it as follows: keep_copy.sh .doc .假设您的脚本名为keep_copy.sh ,您可以按如下方式调用它: keep_copy.sh .doc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM