从路径中删除一个目录组件(字符串操作)

时间:2012-04-25 14:05:53

标签: bash tcsh

我正在寻找从路径中删除字段的最简单,最易读的方法。所以例如,我有/ this /是/ my / complex / path / here,我想使用bash命令从字符串中删除第5个字段(“/ complex”),以便它变为/ this / is /我自己的路。 我可以用

做到这一点
echo "/this/is/my/complicated/path/here" | cut -d/ -f-4
echo "/"
echo "/this/is/my/complicated/path/here" | cut -d/ -f6-

但是我希望只用一个简单的命令就可以完成这个任务,而这需要

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

除了这不起作用。

4 个答案:

答案 0 :(得分:3)

使用cut,您可以指定要打印的逗号分隔字段列表:

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

因此,没有必要使用两个命令。

答案 1 :(得分:0)

使用sed怎么样?

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

答案 2 :(得分:0)

这将删除第5个路径元素

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

只是bash

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

答案 3 :(得分:0)

bash脚本有什么问题吗?

#!/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
相关问题