【发布时间】:2018-12-16 02:08:52
【问题描述】:
sed -e "s/Var4/r {replace.txt} /g" "input.txt" > "output.txt"
Var4:
占位符被替换
替换.txt
包含可变数据
input.txt:
输入文件
输出.txt
输出文件
“input.txt”中每次出现的“Var4”都应替换为“replace.txt”中的变量行,但 sed 将“replace.txt”读取为普通文本而不是文件名:
不正确: TextBox1.Value = "r 替换.txt"
正确: TextBox1.Value = "0000AAAA"
我厌倦了在所有类似的帖子中搜索正确的语法但没有用!
谢谢
输入.txt
TextBox1.Value = "Var4"
Else
TextBox1.Value = "- - - - - - -"
End If
TextBox1.Value = "Var4"
Else
TextBox1.Value = "- - - - - - -"
End If
Output.txt 应该如下所示:
TextBox1.Value = "0000AAAA"
Else
TextBox1.Value = "- - - - - - -"
End If
TextBox1.Value = "0000BBBB"
Else
TextBox1.Value = "- - - - - - -"
End If
替换.txt
0000AAAA
0000BBBB
0000CCCC
我也试过了
sed -e "s/Var4/$(<replace.txt sed -e 's/[\&/]/\\&/g' -e 's/$/\\n/' | tr -d '\n')/g" "input.txt" > "output.txt"
但输出仍然不正确:
TextBox1.Value = "0000AAAA
0000BBBB
0000CCCC
"
Else
TextBox1.Value = "- - - - - - -"
End If
TextBox1.Value = "0000AAAA
0000BBBB
0000CCCC
"
Else
TextBox1.Value = "- - - - - - -"
End If
更新 1:
sed '/Var4/R replace.txt' input.txt | sed '/Var4/{N;s/"Var4"\n\(.*\)/"\1"/}' > "output.txt"
如果 "Var4" 位于行尾,则可以完美运行,但是如果在其后存在任何文本,则输出不正确?
输入.txt
TextBox1.Value = "Var4" Then
Else
TextBox1.Value = "- - - - - - -"
End If
TextBox1.Value = "Var4" Then
Else
TextBox1.Value = "- - - - - - -"
End If
Output.txt 应该如下所示:
TextBox1.Value = "0000AAAA" Then
Else
TextBox1.Value = "- - - - - - -"
End If
TextBox1.Value = "0000BBBB" Then
Else
TextBox1.Value = "- - - - - - -"
End If
替换.txt
0000AAAA
0000BBBB
0000CCCC
使用后的输出.txt:
sed '/Var4/R replace.txt' input.txt | sed '/Var4/{N;s/"Var4"\n\(.*\)/"\1"/}' > "output.txt"
TextBox1.Value = "Var4" Then
0000AAAA
Else
TextBox1.Value = "- - - - - - -"
End If
TextBox1.Value = "Var4" Then
0000BBBB
Else
TextBox1.Value = "- - - - - - -"
End If
有什么建议吗?
【问题讨论】:
-
Windows 本身不包含
sed,除了 Windows 10 中的 WSL 选项,因此您必须从其他来源获得它;大多数此类来源还提供或提供awk和/或perl,其中任何一个都更适合此问题。 -
我在 windows 上安装了 bash 以保持一致性,它可以工作,只是获得正确的语法以获得正确的结果。
标签: file variables text sed replace