-1

I need your help in unix.i have a file where i have a value declared and and i have to replace the value when called. for example i have the value for &abc and &ccc. now i have to substitute the value of &abc and &ccc in the place of them as shown in the output file.

Input File

go to &abc=ddd; if file found &ccc=10; no the value name is &abc; and the age is &ccc;

Output:

go to &abc=ddd; if file found &ccc=10; now the value name is ddd; and the age is 10;

  • If your question involves knowing that `&abc` can be replaced with `ddd` a priori, it's much simpler than if you have to perform lexical analysis and parse what appears to be a domain-specific language. Can you clarify exactly what your question is and what you've done so far? – Brian Cain Jul 23 '13 at 18:18

1 Answers1

1

Try using sed.

#!/bin/bash

# The input file is a command line argument.
input_file="${1}"

# The map of variables to their values
declare -A value_map=( [abc]=ddd [ccc]=10 )

# Loop over the keys in our map.
for variable in "${!value_map[@]}" ; do
  echo "Replacing ${variable} with ${value_map[${variable}]} in ${input_file}..."
  sed -i "s|${variable}|${value_map[${variable}]}|g" "${input_file}"
done

This simple bash script will replace abc with ddd and ccc with 10 in the given file. Here is an example of it working on a simple file:

$ cat file.txt
so boo aaa abc
duh

abc
ccc
abcccc
hmm
$ ./replace.sh file.txt 
Replacing abc with ddd in file.txt...
Replacing ccc with 10 in file.txt...
$ cat file.txt 
so boo aaa ddd
duh

ddd
10
ddd10
hmm
Trenin
  • 2,041
  • 1
  • 14
  • 20
  • i dont have variable fixed it can be anything. It will be something like this (&*=sss). i have have to grep it to the new file and take the value and replace to the original one. – elangovel Jul 24 '13 at 08:45
  • You can make the variables and their values arguments as well. This is just an example. Are you searching for the variables in the same file that you are making the replacements in? If so, then it is trickier because you don't want to replace the place where the variable is defined, but you do want to replace it elsewhere. What is the format of the file? A bash script? Knowing the syntax might help. – Trenin Jul 24 '13 at 12:48