Pergunta

original file called animals looks like this:

dog
cat
dolphin
cat

This command works sed '/dog/i\ Linux Scripting' animals by placing Linux Scripting before dogand I get the following:

 Linux Scripting
dog
cat
dolphin
cat

However if I do a head on animals after this the file is unchanged.

$ head animals
dog
cat
dolphin
cat

How do I do this in such a way that it overwrites the existing file?

Note: for multiple files I would hope to relace animals with *.txt

Foi útil?

Solução

You can make in-file changes by using the -i option.

$ sed '/dog/i\ Linux Scripting' animals
 Linux Scripting
dog
cat
dolphin
cat

$ sed -i '/dog/i\ Linux Scripting' animals

$ cat animals
 Linux Scripting
dog
cat
dolphin
cat

From the man page:

-i[SUFFIX], --in-place[=SUFFIX]

               edit files in place (makes backup if SUFFIX supplied)

So you can create a backup of your original file by passing a suffix. This can be done by saying:

sed -i.bak '/dog/i\ Linux Scripting' animals

This will make in-file changes to your animals file but will create animals.bak file if you ever need the original file.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top