bob
bob

Reputation: 2101

Remove one directory component from path (string manipulation)

I'm looking for the easiest and most readable way to remove a field from a path. So for example, I have /this/is/my/complicated/path/here, and I would like to remove the 5th field ("/complicated") from the string, using bash commands, so that it becomes /this/is/my/path. I could do this with

echo "/this/is/my/complicated/path/here" | cut -d/ -f-4
echo "/"
echo "/this/is/my/complicated/path/here" | cut -d/ -f6-

but I would like this done in just one easy command, something that would like

echo "/this/is/my/complicated/path" | tee >(cut -d/ -f-4) >(cut -d/ -f6-)

except that this doesn't work.

Upvotes: 2

Views: 4520

Answers (4)

Greg Dougherty
Greg Dougherty

Reputation: 3461

Anything wrong with a bash script?

#!/bin/bash        

if [ -z "$1" ]; then 
    us=$(echo $0 | sed "s/^\.\///") # Get rid of a starting ./
    echo "        "Usage: $us StringToParse [delimiterChar] [start] [end]
    echo StringToParse: string to remove something from. Required
    echo delimiterChar: Character to mark the columns "(default '/')"
    echo "        "start: starting column to cut "(default 5)"
    echo "          "end: last column to cut "(default 5)"
    exit
fi


# Parse the parameters
theString=$1
if [ -z "$2" ]; then
    delim=/
    start=4
    end=6
else
    delim=$2
    if [ -z "$3" ]; then
        start=4
        end=6
    else
        start=`expr $3 - 1`
        if [ -z "$4" ]; then
            end=6
        else
            end=`expr $4 + 1`
        fi
    fi
fi

result=`echo $theString | cut -d$delim -f-$start`
result=$result$delim
final=`echo $theString | cut -d$delim -f$end-`
result=$result$final
echo $result

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246754

This removes the 5th path element

echo "/this/is/my/complicated/path/here" | 
  perl -F/ -lane 'splice @F,4,1; print join("/", @F)'

just bash

IFS=/ read -a dirs <<< "/this/is/my/complicated/path/here"
newpath=$(IFS=/; echo "${dirs[*]:0:4} ${dirs[*]:5}")

Upvotes: 0

FatalError
FatalError

Reputation: 54551

With cut, you can specify a comma separated list of fields to print:

$ echo "/this/is/my/complicated/path/here" | cut -d/ -f-4,6-
/this/is/my/path/here

So, it's not really necessary to use two commands.

Upvotes: 4

suvayu
suvayu

Reputation: 4654

How about using sed?

$ echo "/this/is/my/complicated/path/here" | sed -e "s%complicated/%%"
/this/is/my/path/here

Upvotes: 0

Related Questions