5

我是shell脚本的新手。我需要将以下文件结构拆分为文件名分开和文件夹路径分开。在文件名中,我不需要 _ABF1_6,因为它不是文件名的一部分。此外,此 _ABF1_6 从文件路径更改为路径,并且对于所有文件路径都不相同。所以这需要被视为正则表达式..以_ABF1开头。请帮忙!!

示例文件路径:

/EBF/DirectiveFiles/data_report_PD_import_script_ABF1_6 

需要输出:

Folder path: /EBF/DirectiveFiles/ 
Filename: data_report_PD_import_script 
4

3 回答 3

14

出于这个原因,Linux 有特殊的实用程序,basename并且dirname

$ basename /EBF/DirectiveFiles/data_report_PD_import_script_ABF1_6
data_report_PD_import_script_ABF1_6
$ dirname /EBF/DirectiveFiles/data_report_PD_import_script_ABF1_6
/EBF/DirectiveFiles
于 2013-10-20T18:15:23.560 回答
5

UNIX 没有“文件夹”,它有“目录”。

$ cat file
/ECMS/EDEV/ClassicClient/Forms/DirectiveFiles/data_report_PD_import_script_rev1_46_2_16

$ sed -r 's/(.*\/)(.*)_rev1.*/Directory: \1\nFilename: \2/' file
Directory: /ECMS/EDEV/ClassicClient/Forms/DirectiveFiles/
Filename: data_report_PD_import_script

或者如果您愿意,可以使用 GNU awk(用于 gensub()):

$ gawk '{print gensub(/(.*\/)(.*)_rev1.*/,"Directory: \\1\nFilename: \\2","")}' file
Directory: /ECMS/EDEV/ClassicClient/Forms/DirectiveFiles/
Filename: data_report_PD_import_script
于 2013-10-20T12:42:51.267 回答
3

You can use shell parameter expansion for this. :

user> p=/EBF/DirectiveFiles/data_report_PD_import_script_ABF1_6 
user> echo ${p%/*}
/EBF/DirectiveFiles
user> f=${p##/}
user> echo ${f%_ABF1}
data_report_PD_import_script

[Here][1] is a link to the bash documentation on this.

Or with read and GNU sed (not as portable as the above):

read dir file < <(sed -r 's:(.*)/(.*)_ABF1.*:"\1" "\2":' <<<"$p")
echo $dir $file

Output:

"/EBF/DirectiveFiles" "data_report_PD_import_script"
于 2013-10-20T13:44:29.097 回答