简体   繁体   English

在 case 语句中使用 grep 命令

[英]Using grep command inside case statement

So I have this script which im trying to determine the type of the file and act accordingly, I am determining the type of the file using file command and then grep for specific string, for example if the file is zipped then unzip it, if its gzipped then gunzip it, I want to add a lot of different types of file.所以我有这个脚本,我试图确定文件的类型并采取相应的行动,我正在使用文件命令确定文件的类型,然后 grep 用于特定字符串,例如,如果文件被压缩然后解压缩,如果它gzipped 然后 gunzip 它,我想添加很多不同类型的文件。

I am trying to replace the if statements with case and can't figure it out我正在尝试用case替换if语句但无法弄清楚

My script looks like this:我的脚本如下所示:

##$arg is the file itself 

TYPE="$(file $arg)"

if [[ $(echo $TYPE|grep "bzip2") ]] ; then

 bunzip2 $arg

elif [[ $(echo $TYPE|grep "Zip") ]] ; then

  unzip $arg

fi

Thanks to everyone that help:)感谢所有帮助的人:)

The general syntax is一般语法是

case expr in
  pattern) action;;
  other) otheraction;;
  *) default action --optional;;
esac

So for your snippet,所以对于你的片段,

case $(file "$arg") in
  *bzip2*) bunzip2 "$arg";;
  *Zip*)   unzip "$arg";;
esac

If you want to capture the file output into a variable first, do that, of course;如果您想首先将file output 捕获到一个变量中,当然可以这样做; but avoid upper case for your private variables.避免为您的私有变量使用大写字母。

bzip2 and unzip by default modify their input files, though.不过, bzip2unzip默认会修改它们的输入文件。 Perhaps you want to avoid that?也许您想避免这种情况?

case $(file "$arg") in
  *bzip2*) bzip2 -dc <"$arg";;
  *Zip*)   unzip -p "$arg";;
esac |
grep "stuff"

Notice also how the shell conveniently lets you pipe out of (and into) conditionals.还要注意 shell 如何方便地让您 pipe 出(入)条件。

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

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