我有一个从 STDOUT 捕获的多行变量。
我想使用此多行变量将 echo 命令插入到另一个脚本(目标)的第 15 行。
#!/bin/bash
TEST=`cat foo`
echo "$TEST"
sed -i "15i echo \"$TEST\" > someotherfile" target
Run Code Online (Sandbox Code Playgroud)
foo 的内容:
apples
oranges
bananas
carrots
Run Code Online (Sandbox Code Playgroud)
我认为 sed 命令以换行方式读取,我确认我的 foo 有:
user@test$ cat foo | tr -cd '\n' | wc -c
4
Run Code Online (Sandbox Code Playgroud)
当我运行 test.sh 脚本时,我看到了 中的内容$TEST,但收到 sed 命令错误:
user@test$ ./test.sh
apples
oranges
bananas
carrots
sed: -e expression #1, char 18: unknown command: `o'
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?提前致谢。
尝试:
解决方案1:
awk 'NR==15{print;system("cat foo");next} 1' Input_file
Run Code Online (Sandbox Code Playgroud)
无需将完整文件放入变量中,我们可以简单地打印您想要打印的 Input_file 的任何一行。
解决方案2:
line=15; sed -e "${line}r foo" target
Run Code Online (Sandbox Code Playgroud)
或者(在脚本模式下)
cat script.ksh
line=15;
sed -e "${line}r foo" target
Run Code Online (Sandbox Code Playgroud)
您可以在其中更改要从另一个文件插入行的行数。