簡體   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