【问题标题】:Finding the pattern and replacing the pattern inside the file using unix使用 unix 查找模式并替换文件内的模式
【发布时间】:2013-07-23 17:59:14
【问题描述】:

我在 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;

【问题讨论】:

  • 如果您的问题涉及知道&abc 可以先验地替换为ddd,这比您必须执行词法分析并解析似乎是特定于域的语言要简单得多。您能否准确说明您的问题是什么以及到目前为止您做了什么?

标签: linux shell unix shell-exec


【解决方案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

【讨论】:

  • 我没有固定变量,它可以是任何东西。这将是这样的 (&*=sss)。我必须将其 grep 到新文件并取值并替换为原始文件。
  • 您也可以将变量及其值设为参数。这只是一个例子。您是否在进行替换的同一文件中搜索变量?如果是这样,那就更棘手了,因为您不想替换定义变量的位置,但您确实想在其他地方替换它。文件的格式是什么?一个bash脚本?了解语法可能会有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-29
  • 2017-02-14
  • 2013-10-22
  • 1970-01-01
  • 2012-01-25
  • 2021-07-28
  • 1970-01-01
相关资源
最近更新 更多