2012-04-25 6 views
1

パスからフィールドを削除する最も簡単でわかりやすい方法を探しています。例えば、/ this/is/my/complicated/path/hereを持っていて、5番目のフィールド( "/ complex")をbashコマンドを使って文字列から削除して、/ this/is/my/path。 、これが動作しないことを除いてパスから1つのディレクトリコンポーネントを削除する(文字列操作)

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

をご希望のものを私は

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

でこれを行うことができますが、私はこれがちょうど1つの簡単なコマンドで行いたいと思います。

答えて

3

cutを使用すると、印刷にフィールドのカンマ区切りリストを指定することができます。

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

だから、それは2つのコマンドを使用して、本当に必要はありません。

+0

ありがとうございます。これは私の問題を解決します。しかし、私は興味があります:1つのコマンドの結果を2つのコマンドに入力することは可能ですか? – bob

+0

あなたはこれを次のように並べ替えることができます: 'echo hello | tee>(sedの/ l/L/g ')| sed 's/h/H/g''でも、最初の 'sed'の出力は2番目のsedを通過することに注意してください。 (sed 's/l/L/g')>(sed 's/h/H/g') 'になります。 – ams

+1

Hmmm、あなたは、このようなものの出力を渡すのを避けることができます。 'echo hello | tee>(sedの/ l/L/g '>/dev/tty)| sed 's/h/H/g' 'としていますが、ターミナルセッションでしか動作しません。そうでなければ、独自の名前付きパイプが必要です。 – ams

0

sedの使用はいかがですか?

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

私のスクリプトでは、5番目のフィールドの値がわかりません。私はそれが5番目であることを知っています。 – bob

0

これは、第五パス要素

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}") 
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 
関連する問題