如何从一个指令文件中批量替换多个文件中的一行

  • 本文关键字:文件 一行 替换 指令 一个 bash
  • 更新时间 :
  • 英文 :


我们希望用instruction.txt中的相应行替换file001到file600的第3行,在bash语言中有什么可能的解决方案吗?我想也许我可以用sedawk命令写一个脚本,但我无法想出。任何帮助都将不胜感激。谢谢

文件001到文件600包含许多笛卡尔坐标,并且具有相同的格式。例如file001如下:

3.02  5.46  8.94
4.55  3.22  4.35
0.00  0.00  0.00 # this is the wrong line and we want to get it replaced
2.34  3.32  5.47
...

instruction.txt文件为:

file001
3.25  1.13  6.10  #this means to replace the 3rd line of "file001" with "3.25  1.13  6.10"
file002
6.01  1.17  -0.32  #this means to replace the 3rd line of "file002" with "6.01  1.17  -0.32"
...
while read -r line; do 
if [[ $(sed -E 's/^([^ ]*).*/1/' <<< "$line") =~ "file" ]]; then 
file=$line
elif [[ $(sed -E 's/^([^ ]*).*/1/' <<< "$line") =~ [0-9.] ]]; then 
sed -i.bak "3c$line" "$file"
fi
done < instructions.txt

我的解决方案看起来很糟糕,但它很有效:(你可以试试,让我知道它是否适合你。

for i in `cat instruction.txt | awk 'NR % 2 == 1 { printf $0; printf "n" }'`; do
outp=`awk '/'"$i"'/{getline; print}' instruction.txt`;
sed -i '3s/0.00  0.00  0.00/'"$outp"'/' $i;
done

首先,我尝试过滤所有包含文件名的奇数行,并将其分配给变量$i:

cat instruction.txt | awk 'NR % 2 == 1 { printf $0; printf "n" }'

然后得到每个$i的下一行,它是固定值,并将其分配给变量$outp:

outp=`awk '/'"$i"'/{getline; print}' instruction.txt`

最后,用我刚刚收到的两个变量替换错误的第三行。

sed -i '3s/0.00  0.00  0.00/'"$outp"'/' $i

最新更新