shell 将文件的全部内容附加到另一个文件的短语之后

91zkwejq  于 2023-03-09  发布在  Shell
关注(0)|答案(1)|浏览(106)
`echo "Enter input file name:"
 read input_file
 echo "Enter phrase to search for:"
 read phrase
 echo "Enter number of lines to extact:"
 read num_lines
 echo "Enter output file name:"
 read output file
 grep -A $num_lines "$phrase" $input_file>temp.txt
 cat temp.txt >>$output_file
 FILE_TO_INSERT="temp.txt"
 FILE_TO_MODIFY="file2.txt"
 LINE_NUMBER=$(grep -n "ATOMIC" "$FILE_TO_MODIFY" | cut -d ":" -f 1)
 echo $LINE_NUMBER
 sed -i "${LINE_NUMBER}r FILE_TO_INSERT" ${FILE_TO_MODIFY}`

sed命令不执行任何操作。

□ □有何评论?
~
如何将file1.txt的整个内容附加到file2.txt的短语后面?

jucafojl

jucafojl1#

如果我理解你需要什么,在file2.txt中包含"ATOMIC:..."的行之后插入temp.txt,然后简单地调用sed,将"ATOMIC:"定位在一行的开头(带或不带可选的前导空格),这就是所需要的全部,例如:

sed '/^[[:space:]]*ATOMIC:/r temp.txt' file2.txt

除非有一些无法解释的魔法可以让您获得行号,否则就不需要它,您可以在对sed的一次调用中完成所有操作。

    • 使用/输出示例**

例如file2.txt

$ cat file2.txt
Some stuff in the file
that ultimately contains
the line with
ATOMIC:SOME:OTHER:STUFF
in the file

要插入到"ATOMIC:..."后的行中的temp.txt文件,例如

$ cat temp.txt
==
this is the new file to insert
==

和结果(在file2.txt中添加-i选项以进行就地替换)

$ sed '/^[[:space:]]*ATOMIC:/r temp.txt' file2.txt
Some stuff in the file
that ultimately contains
the line with
ATOMIC:SOME:OTHER:STUFF
==
this is the new file to insert
==
in the file

正如你的问题下面的注解中所指出的,如果你需要提供temp.txt作为变量,那么用双引号将sed表达式括起来,这样变量就会展开,并且不要忘记变量名前面的'$'

foo=temp.txt; sed "/^[[:space:]]*ATOMIC:/r $foo" file2.txt

如果我误解了您的问题,请告诉我,并修改您的问题,提供示例数据。我很乐意为您提供进一步帮助。

相关问题