开发者

replace a particular value in a string of key - values

I have a large string which is a collection of key (space)+ value, i.e key followed by one or more space and then value. Now i need to change the value of a particular key using sed, awk, grep etc. in unix environment.

eg. of string: -Key1 Value1 -Key2 Value2 -Key3 Value3

I need a new string that is same as ab开发者_JAVA技巧ove only Value2 will be replaced by NewValue3


echo "-Key1 Value1 -Key2 Value2 -Key3 Value3" | \
    sed -r -e "s/(-Key2\s+)([^-\s]+)(\s+)/\1<newvale>\3/g"
-Key1 Value1 -Key2 <newvale> -Key3 Value3


If I understood you correctly:

sed -e 's/\(.*\)\(-Key2\)\(  *\)\([^ ]*\)\( .*\)/\1\2\3NewValue3\5/'

should do it.


try this

#!/bin/bash
read -p "What is your key?: " key
read -p "What is new value?: " value
echo "-Key1 Value1 -Key2 Value2 -Key3 Value3" | awk -vk="$key" -vv="$value" -F"-"  '
{
    for(i=1;i<=NF;i++){
        if($i ~ k){
            $i=k" "v" "
        }
    }
}1 ' OFS="-"

$ ./shell.sh
What is your key?: Key2
What is new value?: NewVal2
-Key1 Value1 -Key2 NewVal2 -Key3 Value3


Just with bash:

str="-Key1 Value1 -Key2 Value2 -Key3 Value3"
set -- $str  # variable is not quoted to allow for word splitting
new=""
while [[ -n "$1" ]]
do
  case "$1" in
  -Key2) val="newval2" ;;
  *) val="$2" ;;
  esac
  new="$new $1 $val"
  shift 2
done
str="$new"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜