1

I'm writing bash script where I need to store some files as a .bak files and change it content at the beginning(using sed for that).

I'm looking for better way to write it down for my bash script.
cp file.txt file.txt.bak | sed -i '1i#Backup file' file.txt.bak

Maybe someone knew more efficient way to do this or how to do this only by sed or just without pipes.

2

The pipe isn't doing anything at all there. cp has no output, and therefore you cannot pipe its output to another program. I'm guessing you wanted ; or && instead:

## copy the file and then run sed
cp file.txt file.txt.bak; sed -i '1i#Backup file' file.txt.bak

Or

## 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

However, if all you want is a copy of the original file with the first line changed, then sed can indeed do it for you:

sed  '1i#Backup file' file.txt > file.txt.bak
  • I was looking for something like your last example, but then i realized that this changing also my original file.txt. I want only to make change in .bak file – Eddy Jul 12 at 11:00
  • @Eddy your original file isn't affected in any way. Unless you use -i, sed won't touch the input file. It will simply print the modified file to standard output (to the terminal) and leave the original file unchanged. You need -i to change the original. – terdon Jul 12 at 11:01
  • Ohhh... I'm sorry. I tried once more and it seems to be working. Thanks – Eddy Jul 12 at 11:01
  • @Eddy, you should accept the answer by clicking the checkmark on the left side if it was helpful. – pLumo Jul 12 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.