![复制内容已更改的文件](https://linux22.com/image/157075/%E5%A4%8D%E5%88%B6%E5%86%85%E5%AE%B9%E5%B7%B2%E6%9B%B4%E6%94%B9%E7%9A%84%E6%96%87%E4%BB%B6.png)
我正在编写 bash 脚本,我需要将一些文件存储为文件.bak
并在开始时更改其内容(用于sed
此目的)。
我正在寻找更好的方法来为我的 bash 脚本写下它。
cp file.txt file.txt.bak | sed -i '1i#Backup file' file.txt.bak
也许有人知道更有效的方法来做到这一点,或者如何仅通过 sed 或不使用管道来做到这一点。
答案1
管道在那里根本没有做任何事情。cp
没有输出,因此您无法将其输出传送到另一个程序。我猜你想要;
或者&&
相反:
## copy the file and then run sed
cp file.txt file.txt.bak; sed -i '1i#Backup file' file.txt.bak
或者
## copy the file and then run sed BUT only if the copy was successfull
cp file.txt file.txt.bak && sed -i '1i#Backup file' file.txt.bak
但是,如果您想要的只是更改第一行的原始文件的副本,那么 sed 确实可以为您做到这一点:
sed '1i#Backup file' file.txt > file.txt.bak