
私はロープを持っています
/ip/192.168.0.1/port/8080/
ポートとIPを含む2つの独立変数を取得したいと思います。
いいですね。192.168.0.1
そして8080
私が知っている限り、/ip/と/port/は常にそこにあり、私が取得するIPは次のとおりです。
expr /ip/192.168.0.1/port/8080/ : '/ip/\(.*\)/port/'
これは出力されます192.168.0.1
ポートの取得方法がわからず、次のコマンドを試しました。
expr /ip/192.168.0.1/port/8080/ : '/port/\(.*\)/'
しかし、ポートを提供しません。ポートを取得する方法。
答え1
あなたは単に使用することができますcut
次のように:
cut -d '/' -f 3,5
例:
$ echo '/ip/192.168.0.1/port/8080/' | cut -d '/' -f 3,5
192.168.0.1/8080
これにより、区切り文字を使用して/
3番目と5番目のフィールドを切り取り、印刷します。
または、次のようにすることもできます。
$ echo ip=`cut -d '/' -f 3 input_file` port=`cut -d '/' -f 5 input_file`
ip=192.168.0.1 port=8080
答え2
配列を使用する別の純粋なbash方法:
$ s="/ip/192.168.0.1/port/8080/" # initial string
$ a=(${s//// }) # substitute / with " " and make array
$ echo ${a[1]} # Array index 1 (zero-based indexing)
192.168.0.1
$ echo ${a[3]} # Array index 3 (zero-based indexing)
8080
$
または上記と似ていますが、パラメータ拡張の代わりにIFSを使用して文字列を分割します。
$ OLDIFS="$IFS" # save IFS
$ IFS="/" # temporarily set IFS
$ a=($s) # make array from string, splitting on "/"
$ IFS="$OLDIFS" # restore IFS
$ echo "${a[2]}" # Array index 2
192.168.0.1
$ echo "${a[4]}" # Array index 4
8080
$
この方法は、おそらくこの答えの他の2つの方法よりも一般的です。これは、目的のフィールドにスペースが含まれている場合でもまだ機能するためです。
または、位置パラメータを使用してください。
$ s="/ip/192.168.0.1/port/8080/" # initial string
$ set -- ${s//// } # substitute / with " " and assign params
$ echo $2 # Param 2
192.168.0.1
$ echo $4 # Param 4
8080
$
答え3
awkを使用できます。
awk -F\/ '{print $2"="$3, $4"="$5}' input_file
入力ファイルを使用するか、1行ずつ進んでください。
答え4
そしてbash
s=/ip/192.168.0.1/port/8080/
IFS=/ read -r _ _ ip _ port <<<"$s"
echo "$ip"
192.168.0.1
echo "$port"
8080