使用unix查找模式并替换文件内的模式

时间:2013-07-23 17:59:14

标签: linux shell unix shell-exec

我需要你在unix.i中的帮助有一个文件,其中我声明了一个值,并且我必须在调用时替换该值。例如,我有& 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;

1 个答案:

答案 0 :(得分: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脚本将用给定文件中的dd替换abc和ddd和ccc。以下是一个处理简单文件的示例:

$ 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