我有一个从STDOUT捕获的多行变量。
我想使用这个多行变量将echo命令插入到另一个脚本(目标)的第15行。

#!/bin/bash
TEST=`cat foo`

echo "$TEST"

sed -i "15i echo \"$TEST\" > someotherfile" target

foo内容:
apples
oranges
bananas
carrots

我认为sed命令读取了行feeds,我确认foo已经:
user@test$ cat foo | tr -cd '\n' | wc -c
4

运行test.sh脚本时,我看到了$TEST中的内容,但是sed命令出现错误:
user@test$ ./test.sh
apples
oranges
bananas
carrots
sed: -e expression #1, char 18: unknown command: `o'

我做错什么了?
提前谢谢。

最佳答案

尝试:
解决方案1:

awk 'NR==15{print;system("cat foo");next} 1' Input_file

不需要将完整的文件放入变量中,我们可以简单地打印它,无论您想打印哪一行输入文件。
解决方案2:
line=15; sed -e "${line}r foo" target

或(在脚本模式下)
cat script.ksh
line=15;
sed -e "${line}r foo" target

您可以在其中更改要从其他文件插入行的行数。

09-10 01:14
查看更多