Search code examples
bashtcsh

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.


Solution

  • 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.