我有两个bash数组,一个包含文件名,另一个包含行号:
filepaths=(fig/par1.tex fig/par2.tex fig/par3.tex)
lines=(5 10 15)我还有另一个文件(file.tex),我想将$filepaths中列出的每个文件的内容插入到$lines$中相应的行号,替换file.tex中该行的内容。例如,fig/par1.tex的内容将替换file.tex的第5行,fig/par2.tex的内容将替换file.tex的第10行。
我尝试使用for循环,遍历数组索引:
for ((i=0;i<${#filepaths[@]};++i)); do
sed -i "${lines[i]}r ${filepaths[i]}" file.tex
done但是我在循环的每次迭代中都会得到一个错误:
sed: 1: "file.tex": invalid command code f建议的问题Bash tool to get nth line from a file提供了按行号打印文件中特定行的答案。这并没有回答我的问题,这个问题与迭代数组变量以在行号处插入文本有关。
发布于 2020-04-02 18:56:45
您可以使用以下脚本:
s=
# loop through array and build sed command
for ((i=0;i<${#lines[@]};++i)); do
printf -v s '%s%s\n%s\n' "$s" "${lines[i]}r ${filepaths[i]}" "${lines[i]}d"
done
# check sed command
# echo "$s"
# run a single sed
sed -i.bak "$s" file.tex因为替换字符串中有/,所以在sed中使用替换分隔是很重要的,例如~。
https://stackoverflow.com/questions/60980245
复制相似问题