views:

60

answers:

4

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 above only Value2 will be replaced by NewValue3

A: 

If I understood you correctly:

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

should do it.

Alok
A: 

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
ghostdog74
+1  A: 
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
Dyno Fu
A: 

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"
glenn jackman