如何在shell中替换这样的子串?

时间:2017-07-06 02:19:21

标签: linux shell

我想用linux shell中的新子字符串替换oldstring中的substring:

旧字符串可能是以下一行:

-i eth0 -a abc -w a.pcap host 10.10.10.10
-i eth0 -a abc -w   a.pcap host 10.10.10.10

substring就是其中之一:

-w a.pcap
-w  a.pcap

new substring,' / home / test / test'由' PWD'定义在shell中:

-w /home/test/test/a.pcap

所以新字符串是:

-i eth0 -a abc -w /home/test/test/a.pcap host 10.10.10.10

我不知道如何做到这一点,因为我已经写了这样的脚本,但是这个如果' a.pcap'改为' -& eth;' -i eth'将被替换为' -i / home / test / test / eth'。

PWD=`pwd`
PARAM="$@"
OLD_W_PATH=
NEW_W_PATH=

process_w()
{
    if [ -z "$1" ]
    then
        echo "empty -w path param."
        exit -1
    else
        if [[ $1 == /*  ]]
        then
            # this is absolute path
            NEW_W_PATH=$1
        else
            NEW_W_PATH="${PWD}""/""$1"
        fi
    fi
}

while getopts "i:d:p:w:" arg; do
    case $arg in
        h | --help)
            echo "ovs-dump -i dpdkb2 [-d in] [-p tcp] [host 192.168.102.2][port 80] [-w /test.pcap]"
            exit 0
            ;;
        w )
            OLD_W_PATH=$OPTARG
            #NEW_W_PATH is set in process_w
            process_w $OPTARG
            ;;
        ?)
            ;;
    esac
done

# process PARAM
PARAM=${PARAM/$OLD_W_PATH/$NEW_W_PATH}
echo $PARAM

那么shell中的常规表达会更好吗?谢谢〜

1 个答案:

答案 0 :(得分:0)

不要尝试将命令转换为字符串 - 它以数组开头; 保存为数组。

#!/bin/bash

# create an empty array called "args"
args=( )

canonicalize() {
  case $1 in
    /*) printf '%s\n' "${PWD}/$1"
    *)  printf '%s\n' "$1"
  esac
}

while (( $# )); do
  case $1 in
    # if $1 is -w, then we canonicalize the path and shift a second argument off
    -w) args+=( -w "$(canonicalize "$2")" ); shift;;

    # other arguments get copied as-is
    *)  args+=( "$1" ) ;;
  esac
  shift
done

# copy that updated array back to "$@"
set -- "${args[@]}"