简体   繁体   English

在bash中解析字符串

[英]parsing string in bash

I have a bunch of C++ files in a directory called src . 我在名为src的目录中有一堆C++文件。 I needed to find all the files that have *Test.cc , but without the .cc file type, so it would just be [filename]Test . 我需要查找所有具有*Test.cc的文件,但没有.cc文件类型,因此它只是[filename]Test I currently have: 我目前有:

  1 FILES=./src/*Test.cc
  2 
  3 for f in $FILES
  4     do
  5         echo "processing $f"
  6 done

so I only need the name of the file, without ./src/ and without .cc . 所以我只需要文件名,没有./src/.cc For example, the above script would produce: 例如,上面的脚本将产生:

processing ./src/UtilTest.cc

And I only need UtilTest . 而且我只需要UtilTest How can I accomplish that? 我该怎么做?

在第4行和第5行之间插入此行将导致bash代码段产生所需的输出:

f=$(basename $f .cc)

You can accomplish that with this one liner commands: 您可以使用此一个内衬命令完成此操作:

First is storing it in a file for reference: 首先是将其存储在文件中以供参考:

find ./src/ -name *Test.cc | tee samp.txt

Then printing it or it depends on what you want do with the file: 然后打印它或取决于您要对文件执行的操作:

cat samp.txt | while read i; do echo `basename $i .cc`; done;

Just to show you another option: for later versions of bash (not sure anymore which version), you can use arrays and string manipulation: 只是向您展示另一个选择:对于更高版本的bash(不再确定哪个版本),可以使用数组和字符串操作:

files=(.src/*Test.cc)      # create bash array (space-separated)

for f in ${files[@]##./}   # loop through array, stripping leading path 
do 
     echo ${f%%.*}         # f is now array element; strip its extension
done

Obviously, as in your own example, when the file name contains spaces or has multiple extentions (eg, Your File Test.cc.hpp ), there will be problems. 显然,就像您自己的示例一样,当文件名包含空格或具有多个扩展名时(例如, Your File Test.cc.hpp ),将出现问题。

Anyway, this sidesteps the call to basename and does not require a temp file, as in the other two answers; 无论如何,这就像其他两个答案一样,避开了对基basename的调用,并且不需要临时文件。 the only downside is its limited portability due to bash version requirements. 唯一的缺点是由于bash版本要求,其有限的可移植性。

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

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