Thursday, May 17, 2012

Bash tip to extract path from absolute filename

Thanks to Bash advanced features. We have seen Search and replace technique in last post. Now lets try another technique to extract content from a variable based on some filter.

Lets take a use case.
1. Extract path from a file name which is an absolute file path.

For this, we need to extract path except the filename. Lets see how to achieve this using advance bash scripting.

Syntax is:
S1 - String on which filter is required
S2 - String which needs to be removed from the end.

Which means in the fillename, from the end it removes characters till it finds "/", including "/"

Example1:  Extract path from file name

[bash] # var="/home/product/module/libTest.a"

[bash] # var=${var%/*}
[bash] # echo $var


Example2:  Remove world from "Helloworld"

[bash] # var="Helloworld"

[bash] # var=${var%world}

[bash] # echo $var
[bash] #

Pin It
Related Posts Plugin for WordPress, Blogger...