LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   String Manipulation question! (https://www.linuxquestions.org/questions/linux-newbie-8/string-manipulation-question-862655/)

nsingh49 02-14-2011 02:28 PM

String Manipulation question!
 
I have a string and keeping the delimiter to be /, I would like extract highlighted string

/u01/oradata/mydatabase/ABCF.dbf

I can extract the last field after the delimiter, but all the fields before is the challenge to me.

Thanks

Nirmal

nsingh49 02-14-2011 02:44 PM

Ok I figured out

basename /u01/oradata/mydatabase/ABCF.dbf

gives me ABCF.dbf

dirname /u01/oradata/mydatabase/ABCF.dbf

gives me /u01/oradata/mydatabase


Cheers...

vikas027 02-14-2011 02:49 PM

Try this.

Code:

echo "/u01/oradata/mydatabase/ABCF.dbf" | awk -F"/" '{print "/"$1"/"$2"/"$3}'
In future post requests like these in Programming Forum.

grail 02-15-2011 12:43 AM

Or if you actually want to use string manipulation in bash:
Code:

LINE="/u01/oradata/mydatabase/ABCF.dbf"
echo ${LINE##*/}    # this gives you filename
echo ${LINE%/*}    # this gives you path to file


MTK358 02-15-2011 08:32 AM

Or sed:

Code:

sed 's/^\(.*\)/[^/]*$/\1/'
But if you're dealing with actual paths to files, you should really use basename and dirname.

If the issue is solved, mark the thread as solved.

nsingh49 02-15-2011 09:08 AM

Vikas, you suggested:
echo "/u01/oradata/mydatabase/ABCF.dbf" | awk -F"/" '{print "/"$1"/"$2"/"$3}'

In my case I don't know how many fields are there. It would be 3,4 or 5 and who know.

Thanks

Nirmal

catkin 02-15-2011 12:44 PM

Quote:

Originally Posted by MTK358 (Post 4259120)
But if you're dealing with actual paths to files, you should really use basename and dirname.

Hi MTK358 :) Does that mean there is some reason not to use grail's suggestions? I use them exclusively (never basename or dirname) and have not yet encountered a problem.

MTK358 02-15-2011 01:02 PM

Quote:

Originally Posted by catkin (Post 4259364)
Hi MTK358 :) Does that mean there is some reason not to use grail's suggestions? I use them exclusively (never basename or dirname) and have not yet encountered a problem.

I guess they would work fine, but if they provide you with utilities just for getting the filename and directory name from a path, why not use them? It seems like it would be more readable, too.


All times are GMT -5. The time now is 11:56 AM.