Substring from the file name

Hi

I need substring from the file name of list of files. I mean i will have to load all the files into database which are there in the Directory.

I need to make the directory with the date(which is substring of the filename Eg: Filename_Name_2012013001010101.txt, So the directory should be 20120130).

I need to load this file into oracle and need to move the file into above created directory.

It should happend till all files are loaded into database. Could someone give the ideas?

Thanks

$ echo Filename_Name_2012013001010101.txt | awk '/^[0-9]/{print substr($1,1,8)}' RS='[_.]'
20120130

Create a file with list of file names to be loaded, use SQL loader to load them to Oracle DB.

Verify the result of load operation, if successful then run below bash script to perform the move:

#!/bin/bash
while read filename
do
        fname=${filename##*_}
        dir=${fname:0:8}
        echo mkdir -p "$dir"
        echo mv "$filename" "${dir}/"
done < file.list

Note: Remove the highlighted echo if the output looks good.

Thanks for you reply,

But forgot to tell you that Filename may have numbers as well apart from Date and Full file name will have n. number of underscores. What i need is we should pick up the date from end of the file name as it has date and time before the extension of file.

If you want to extract the date from end of the file name, then try this:

filename="Filename_Name_2012013001010101.txt"
fname=${filename%%.*}
fname=${fname##*_}
dir=${fname:0:8}

Thanks Bipin,

I tried running the script using your code but it gives an error saying bad substitution at "dir=${fname:0:8}"

Which shell are you using?

bakunin

I am using Ksh

*sigh*

this is only half the necessary information: there is Korn shell 88 and Korn shell 93 and they differ in some respects (ksh93 has some features ksh88 has not). Which one are you using? And while you are at it: the name and version of the OS sometimes also matters, so you better [i]always[/i state this information ideally at the top of any new thread.

bakunin

Hi

Would you please let me know how do i find out the type ksh on Server?

Thanks in advance

Post the o/p of below commands:

uname
ksh --version

bipinajith was a bit carefree here:

Which OS:

uname -a

Some OSes (HP-Ux, Solaris) will show the version too this way, some have other commands for this:

  • AIX
    text oslevel -g

  • Linux - Redhat and consorts (Fedora, CentOS, ...)
    text cat /etc/redhat-release

  • Linux - Slackware
    text cat /etc/slackware-version

Which ksh-version:

I am not sure if every ksh version understands this - the AIX version doesn't, for instance. The "--" to introduce worded options is a Linux speciality and not common everywhere. What is guaranteed to work is:

print - ${.sh.version}

or

set -o vi
<ESC><^V>

I hope this helps.

bakunin

1 Like