如何在 shell 脚本中使用 sed 命令替换一个目录中存在的 txt 文件中的字符串?

How to replace using sed command in shell scripting to replace a string from a txt file present in one directory by another?

我对 shell 脚本编写非常陌生,正在尝试学习 "sed" 命令功能。

我有一个名为 configurations.txt 的文件,其中定义了一些变量,并为每个变量初始化了一些字符串值。 我正在尝试用定义的变量值替换其他目录中存在的文件 (values.txt) 中的字符串。文件的名称是 values.txt.

configurations.txt 中存在的数据:-

mem="cpu.memory=4G"
proc="cpu.processor=Intel"

values.txt 中的数据(/home/cpu/script 中的数据):-

cpu.memory=1G
cpu.processor=Dell

我正在尝试制作一个名为 repl.sh 的 shell 脚本,我现在没有很多代码,但这是我得到的:-

#!/bin/bash
source /home/configurations.txt
sed <need some help here>

预期输出是在应用适当的正则表达式后,当我 运行 脚本 sh repl.sh 时,在我的 values.txt 中,它必须包含以下数据:-

cpu.memory=4G
cpu.processor=Intell

原来是1G和Dell。

非常感谢您的快速帮助。谢谢

这道题缺少某种抽象套路,看起来像"help me do something concrete please"。因此,任何人都不太可能为该问题提供完整的解决方案。

你应该做什么尝试把这个任务分成许多小块。

1) 遍历 configuration.txt 并从每一行获取值。为此,您需要从 value="X=Y" 字符串中获取 XY

这个正则表达式在这里可能会有帮助 - ([^=]+)=\"([^=]+)=([^=]+)\"。它包含 3 个由 " 分隔的匹配组。例如,

>> sed -r 's/([^=]+)=\"([^=]+)=([^=]+)\"//' configurations.txt
mem
proc
>> sed -r 's/([^=]+)=\"([^=]+)=([^=]+)\"//' configurations.txt
cpu.memory
cpu.processor
>> sed -r 's/([^=]+)=\"([^=]+)=([^=]+)\"//' configurations.txt
4G
Intel

2) 对于每个 XYvalues.txt 中找到 X=Z 并将其替换为 X=Y.

例如,让我们将 values.txt 中的 cpu.memory 值更改为 4G:

>> X=cpu.memory; Y=4G; sed -r "s/(${X}=).*/${Y}/" values.txt
cpu.memory=4G
cpu.processor=Dell

使用 -i 标志进行适当的更改。

这是一个基于 awk 的答案:

$ cat config.txt
cpu.memory=4G
cpu.processor=Intel

$ cat values.txt
cpu.memory=1G
cpu.processor=Dell
cpu.speed=4GHz

$ awk -F= 'FNR==NR{a[]=; next;}; {if( in a){=a[]}}1' OFS== config.txt values.txt 
cpu.memory=4G
cpu.processor=Intel
cpu.speed=4GHz

说明:首先读取config.txt并保存在内存中。然后阅读values.txt。如果在 config.txt 中定义了特定值,请使用内存中保存的值 (config.txt)。