繁体   English   中英

如何在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”命令功能。

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

configuration.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>

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

cpu.memory=4G
cpu.processor=Intell

最初是1G和Dell。

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

这个问题缺少某种抽象的例程,看起来像“请帮助我做一些具体的事情”。 因此,几乎没有人会为该问题提供完整的解决方案。

您应该做的是尝试将此任务拆分为小块。

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

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

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

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

例如,让我们改变cpu.memory价值values.txt4G

>> X=cpu.memory; Y=4G; sed -r "s/(${X}=).*/\1${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[$1]=$2; next;}; {if($1 in a){$2=a[$1]}}1' OFS== config.txt values.txt 
cpu.memory=4G
cpu.processor=Intel
cpu.speed=4GHz

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM