Monday, October 29, 2012

How to remove a component of absolute path?



How to remove a component of absolute PATH?

Let us consider an absolute path "/export/home/guru/prog/perl".
$ x="/export/home/guru/prog/perl" 
The requirement is to remove the 4th component of the absolute path so that it becomes "/export/home/prog/perl".

1. cut command:
$ echo $x | cut -d"/" -f -3,5-
/export/home/prog/perl
cut is the straightforward option. Since we want to drop the 4th field, cut fields 1 to 3, and then from 5 onwards till the end.

2. sed:
$ echo $x  | sed 's|[^/]*/||4'
/export/home/prog/perl
Remove non-slash(/) characters till a slash is found, and do this only on the 4th occurrence. Using this, the 4th component gets removed.

3. awk:
$ echo $x | awk -F"/" '{$4="";}1' OFS="/" | tr -s "/"
/export/home/prog/perl
Using / as delimiter, the 4th field is initialized. However, this will leave with 2 slashes after "home". In order to squeeze the extr slash, tr command is used.

4. Perl:
$ echo $x | perl -F"/" -ane 'print join("/", @F[0 .. 2],@F[4 .. $#F]);'
/export/home/prog/perl
A nice option. Using the auto-split option(-a) with "/" as delimiter, the path is split into the special array @F. The array components are joined using "/" and printed by excluding the 4th(index 3) component.

5. Another Perl solution:
$ echo $x | perl -F"/" -ane 'splice(@F,4,1); print join "/",@F;'
/export/home/guru/perl
Using splice, we can simply delete the element in offset 4 which is the 4th component. And then the remaining elements are joined and printed.
Related Posts Plugin for WordPress, Blogger...

No comments:

Post a Comment