Reputation:
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
Upvotes: 5
Views: 10024
Reputation: 47099
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"
Upvotes: 3
Reputation: 33327
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
Upvotes: 15
Reputation: 203645
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
Upvotes: 5