5

I am a novice in shell scripting. I need to split this following file structure as filename separate and folder path separate. In the filename, I don't need _ABF1_6, as it is not part of the filename. Also this _ABF1_6 changes from file path to path and is not the same for all filepaths. So this needs to be considered as regular expression..beginning with _ABF1. Please help!!

Sample filepath:

/EBF/DirectiveFiles/data_report_PD_import_script_ABF1_6 

Output required:

Folder path: /EBF/DirectiveFiles/ 
Filename: data_report_PD_import_script 
  • Why on earth would you change the directory path and change `_rev1_6` to `_ABF1_6` in your sample input after you'd posted the question and received answers? It makes no difference to your question but now makes it harder for people to understand the differences between the answers. – Ed Morton Oct 21 '13 at 11:26

3 Answers3

15

Linux has special utilities for this reason, basename and 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
user000001
  • 32,226
  • 12
  • 81
  • 108
5

UNIX doesn't have "folders", it has "directories".

$ 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

or with GNU awk (for gensub()) if you prefer:

$ gawk '{print gensub(/(.*\/)(.*)_rev1.*/,"Directory: \\1\nFilename: \\2","")}' file
Directory: /ECMS/EDEV/ClassicClient/Forms/DirectiveFiles/
Filename: data_report_PD_import_script
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
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"
Thor
  • 45,082
  • 11
  • 119
  • 130