【发布时间】:2020-05-27 22:22:50
【问题描述】:
我正在编写一个脚本,用于遍历目录中的一组文件,在一个文件 (srcFile) 中搜索字符串 (stringA),复制其后面的行 (stringToCopy),然后将其粘贴到另一个文件 (outputFile) 中的另一个搜索字符串 (stringB) 之后的行上。我目前的复制/粘贴脚本如下
stringA="This is string A"
stringB="This is string B"
srcFile=srcFile.txt
outpuFile=outputFile.txt
replacement="/$stringA/{getline; print}"
stringToCopy="$(awk "$replacement" $srcFile)"
sed -i "/$stringB/!b;n;c${stringToCopy}" $outputFile
脚本运行良好,除非stringToCopy 最终包含花括号。例子是
srcFile.txt:
This is string A
text to copy: {0}
输出文件.txt:
This is string B
line to be replaced
脚本完成后,我希望outputFile.txt 是
This is string B
text to copy: {0}
但是 sed 被
sed: -e expression #1, char 106: unknown command: `m'
我尝试对有问题的字符串进行硬编码,并尝试转义花括号和引用字符串的不同变体,但没有找到成功的组合,我不知道如何使它工作。
编辑
我有一个糟糕的时刻,忘记了我的stringA 也有花括号,这恰好导致我的 awk 命令对多行进行数学运算。这导致我的stringToCopy 中有换行符,这是我真正的问题,而不是花括号。所以真正的问题是,如何让 awk 将花括号视为文字字符,以便
srcFile.txt
This is string A: {0}
text to copy: {0}
This is string A:
Other junk
还有stringA="This is string A: {0}"
未将stringToCopy 设置为
text to copy: {0}
Other junk
【问题讨论】:
-
工作方式是将变量内容写入临时文件,使用
rsed命令。