如何使用bash脚本从文本文件替换一个文件中变量的值? [英] How to replace a value of variable in one file from text file using bash script?
问题描述
我有一个Makefile,我想在运行时使用bash脚本更改/替换变量的值.
I have one Makefile in which I want to change/replace the value of a variable during runtime with bash script.
Makefile内容:-
Makefile content:-
SUBDIRS = common alarm coders crypto communication conup database \
dynamicProtocols dynamethods dynamic TTStorage tables \
jobManager logManager processManager \
collection processing distribution mediationManager adaptations tools performanceMonitor \
cli
现在,我希望将此SUBDIRS值替换为文本文件的内容.
Now I want this SUBDIRS value to be replaced with content of my text file.
文本文件内容:-
database
common
jobManager
coders
process
此文本文件的内容可能在1到20个字之间.
This text file content may vary from 1-20 words.
现在,正如另一个线程中所建议的那样,我们在以下解决方案中使用了单个单词:-
Now as suggested in another thread, we used below solution for single word:-
sed -r 's/(SUBDIRS = ).*/\1protocols/' Makefile
但这仅将第一行替换为协议".生成的输出是:-
But this only replaces first line with 'protocols'. Generated output is:-
SUBDIRS = protocols
dynamicProtocols dynamethods dynamic TTStorage tables \
jobManager logManager processManager \
collection processing distribution mediationManager adaptations tools performanceMonitor \
cli
所需的输出是:-
SUBDIRS = protocols
现在,我们要读取文本文件的所有内容并分配给SUBDIRS.如下所示:
Now, we want to read all contents of text file and assign to SUBDIRS. Shown below:
SUBDIRS = database common jobManager coders process
请提出建议.
推荐答案
sed 方法:
sed approach:
sed -z -e 's/\n//g' -e "s/\(SUBDIRS = \).*/\1$(tr '\n' ' ' < words)\n/;" Makefile
-
words
是一个文件名,包含1-20个单词以内的words
is a filename containing from 1-20 words-z
-将输入视为一组行,每行以零字节结尾-z
- treat the input as a set of lines, each terminated by a zero bytes/\ n//g
-删除Makefile
$(tr'\ n'''< words)
-将换行符转换为words
文件$(tr '\n' ' ' < words)
- translating newlines into spaces in thewords
file输出:
SUBDIRS = database common jobManager coders process
这篇关于如何使用bash脚本从文本文件替换一个文件中变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!