bash匹配2个文件的内容,并在匹配行后面附加字符串



我在Mac OS上工作,我是shell的新手。我有两个文件一个Main.txt其内容为:

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'Sample' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for Sample
pod 'FirebaseCore', '7.8.0'
pod 'GoogleUtilities', '7.2.2'
pod 'FirebaseMessaging', '7.8.0'
pod 'FirebaseCrashlytics', '7.8.0'
pod 'FirebaseAnalytics', '7.8.0'
pod 'FirebasePerformance', '7.8.0'
pod 'Fluper', '2.0.0.1'
pod 'lottie-ios', '2.5.0
pod 'XYZ', :git => 'git@bitbucket.org:myteam/xyz.git', :commit => 'a32d154'
pod 'ABC', :git => 'git@bitbucket.org:mytmteam/abc.git', :branch => 'debug101'
pod 'myProject-auth-test', '2.0.0'
pod 'myProject-network-test', '2.0.1'
pod 'myProject-core-test', '2.0.1'
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '11.0'
if config.name.include?("Release") || config.name.include?("Adhoc")
config.build_settings['LLVM_LTO'] = 'YES_THIN'
elsif config.name.include?("Debug")
config.build_settings['LLVM_LTO'] = 'NO'
end
end
end
end
另一个是Module.txt其内容为:
pod 'FirebaseCore'
pod 'GoogleUtilities'
pod 'FirebaseMessaging'
pod 'FirebaseCrashlytics'
pod 'FirebaseAnalytics'
pod 'FirebasePerformance'
pod 'Fluper'
pod 'lottie-ios'
pod 'myProject-auth-test'
pod 'myProject-network-test'
pod 'myProject-core-test'

我想添加

, :binary => true

在Main.txt中所有匹配行的末尾,所以预期的输出应该是(content of Main.txt):

pod 'FirebaseCore', '7.8.0', :binary => true
pod 'GoogleUtilities', '7.2.2', :binary => true
pod 'FirebaseMessaging', '7.8.0', :binary => true
pod 'FirebaseCrashlytics', '7.8.0', :binary => true
pod 'FirebaseAnalytics', '7.8.0', :binary => true
pod 'FirebasePerformance', '7.8.0', :binary => true
pod 'Fluper', '2.0.0.1', :binary => true
pod 'lottie-ios', '2.5.0, :binary => true
pod 'XYZ', :git => 'git@bitbucket.org:myteam/xyz.git', :commit => 'a32d154' 
pod 'ABC', :git => 'git@bitbucket.org:mytmteam/abc.git', :branch => 'debug101'
pod 'myProject-auth-test', '2.0.0', :binary => true
pod 'myProject-network-test', '2.0.1', :binary => true
pod 'myProject-core-test', '2.0.1', :binary => true

以下条目被忽略,因为它们不在Module.txt文件

pod 'XYZ', :git => 'git@bitbucket.org:myteam/xyz.git', :commit => 'a32d154'
pod 'ABC', :git => 'git@bitbucket.org:mytmteam/abc.git', :branch => 'debug101'

这将匹配Main.txt中Modules.txt中的每一行,并将, :binary => true附加到该行。它很脆弱,但假设输入数据的格式与问题中给出的格式相似,它将工作得很好。

while IFS="" read -r line; do
sed -i "/^${line}/s/$/, :binary => true/" Main.txt
done < Module.txt

这可能适合您(GNU sed):

sed 's#.*#/&/ba#' modulesFile | sed -f - -e 'b;:a;s/$/, :binary => true/' file

modulesFile创建一个sed命令文件,并将其管道连接到对file的sed运行的第二次调用

注意:如果file中的一行与modulesFile中的地址不匹配,则不会进行修改,即b命令在替换之前爆发。

将Module.txt转换为合适的正则表达式,然后就地修改Main.txt:

match=$(sed '$!s/.*/^&.*\|/; $s/.*/^&.*/' Module.txt | tr -d 'n')
sed -i "/$match/s/$/, :binary => true/" Main.txt

最新更新