-1

我需要您在 unix 中的帮助。我有一个文件,其中声明了一个值,并且在调用时我必须替换该值。例如,我有 &abc 和 &ccc 的值。现在我必须用 &abc 和 &ccc 的值代替它们,如输出文件所示。

输入文件

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

输出:

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

4

1 回答 1

1

尝试使用 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

这个简单的 bash 脚本将在给定文件中将 abc 替换为 ddd 并将 ccc 替换为 10。这是一个处理简单文件的示例:

$ 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
于 2013-07-23T18:19:59.660 回答