Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 如何从特定行开始将数据从文件复制到另一个文件_Linux_Bash_Unix_Sed - Fatal编程技术网

Linux 如何从特定行开始将数据从文件复制到另一个文件

Linux 如何从特定行开始将数据从文件复制到另一个文件,linux,bash,unix,sed,Linux,Bash,Unix,Sed,我有两个文件data.txt和results.txt,假设data.txt中有5行,我想复制所有这些行,并从行号4开始将它们粘贴到文件results.txt 以下是一个示例: Data.txt文件: stack ping dns ip remote # here are some text # please do not edit these lines # blah blah.. this is the 4th line that data should go on. Results.tx

我有两个文件
data.txt
results.txt
,假设
data.txt
中有5行,我想复制所有这些行,并从行号4开始将它们粘贴到文件
results.txt

以下是一个示例:

Data.txt文件:

stack
ping
dns
ip
remote
# here are some text
# please do not edit these lines
# blah blah..
this is the 4th line that data should go on.
Results.txt文件:

stack
ping
dns
ip
remote
# here are some text
# please do not edit these lines
# blah blah..
this is the 4th line that data should go on.
我尝试了各种组合的sed
sed
,但我无法让它工作,我不确定它是否也适合这个目的

sed -n '4p' /path/to/file/data.txt > /path/to/file/results.txt
上述代码仅复制第4行。这不是我想要实现的。如上所述,我需要复制
data.txt
中的所有行,并将它们粘贴到
results.txt
中,但它必须从第4行开始,而不修改或覆盖前3行

非常感谢您的帮助

编辑:

stack
ping
dns
ip
remote
# here are some text
# please do not edit these lines
# blah blah..
this is the 4th line that data should go on.
我想覆盖从中的行号4开始复制的数据 文件results.txt。所以,我想留下前3行,没有 修改并用复制的数据覆盖文件的其余部分 从
data.txt
文件


您可以使用进程替换为
cat
提供一个fifo,它将能够从中读取:

cat <(head -3 result.txt) data.txt > result.txt
cat result.txt

这里有一种方法可以很好地使用cron。丢失数据或损坏文件的可能性更小:

# preserve first lines of results
head -3 results.txt > results.TMP

# append new data
cat data.txt >> results.TMP

# rename output file atomically in case of system crash
mv results.TMP results.txt
如果您可以使用awk:

awk 'NR!=FNR || NR<4' Result.txt Data.txt

awk'NR=FNR | | nr一个简单的解决方案是增加一个包含前三行的“头”文件,该头三行将与另一个输入文件合并到结果文件中。我仍在寻找一种方法来满足你的要求,但这绝对是可行的。那没有用。它从results.txt中删除了前3行。我想让它们保持未修改状态,并覆盖其余的行。我已经编辑了我的问题,请看一下。谢谢!这真的很有效。我认为这是一个公认的答案,不客气。
.TMP
技术是我在各种情况下在自己的脚本中大量使用的技术。除原子更新外,由于更新的性质,它们中的大多数无法就地修改。谢谢您的回答。我非常感激。但不幸的是,它没有工作,它覆盖了前3行,我想保持不变。克雷格·埃斯蒂的回答对我有用。再次谢谢你。@JerryB真奇怪,我在Cygwin身上试过,效果不错。结果文件的前三行有什么值得注意的地方吗?我现在用您的确切代码再次尝试,但它再次覆盖了前三行。我尝试使用双箭头
>
,所以这次它保留了3行,但它复制了它们,脚本每次运行都会将前3行和复制的行加倍。我不确定到底是什么让它不起作用。但是我必须非常感谢您的帮助,非常感谢。我猜文件在被子进程读取之前被覆盖,因此,
不返回任何内容,结果只包含数据文件。我不知道是什么原因造成的。。。不客气,谢谢你的反馈!