2012-04-25 72 views
1

我正在尋找最簡單和最可讀的方法來從路徑中刪除一個字段。例如,我有/這/是/我/複雜/路徑/在這裏,我想從字符串中刪除第五個字段(「/複雜」),使用bash命令,以便它/ /這/是/我自己的路。 我能做到這一點與從路徑中刪除一個目錄組件(字符串操作)

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-) 

除了這行不通。

回答

3

隨着cut,你可以指定一個逗號分隔的字段列表打印:

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

所以,這是不是真的有必要使用兩個命令。

+0

謝謝。這解決了我的問題。但是,我很好奇:是否可以將一個命令的結果提供給兩個命令? – bob 2012-04-25 14:44:22

+0

你可以這樣做:'echo hello | (sed's/l/L/g')| sed's/h/H/g''但是請注意,第一個'sed'的輸出也會通過第二個sed,或者像你原來的文章'echo hello | (sed's/l/L/g')>(sed's/h/H/g')',但你會得到三份。 – ams 2012-04-25 15:52:09

+1

嗯,你可以避免像這樣''echo hello | tee>(sed's/l/L/g'>/dev/tty)| sed's/h/H/g',但它只能在終端會話中使用,當然,否則,您需要您自己的命名管道。 – ams 2012-04-25 15:57:59

0

如何使用sed?

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

在我的劇本中,我不知道第五場的價值,我只知道它是第五場。 – bob 2012-04-25 14:12:39

0

這消除了第五路徑元素

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

只是慶典

IFS=/ read -a dirs <<< "/this/is/my/complicated/path/here" 
newpath=$(IFS=/; echo "${dirs[*]:0:4} ${dirs[*]:5}") 
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 
相關問題