-3

This question already has an answer here:

$ cat text.txt
my name is Steven
my age is 10
i like dogs

What command will be fitting so that echo "Kate" will replace Steven on text.txt?

marked as duplicate by G-Man Says 'Reinstate Monica', roaima, jimmij, don_crissti, Anthon Aug 28 '15 at 11:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3

If it must be with echo "Kate", use awk:

echo "Kate" | awk 'NR==FNR{a=$0;next} sub("Steven", a, $0)1' - file
  • The standard input is Kate from echo "Kate", piped to awk.
  • awk then reads the stdin (-). The condition NR==FNR is true when the first file is processes (stdin). The variable a is set to that value.
  • Then the input of file is processed and sub() replaces Steven with the value of a.
  • the sub()1 is the pattern in the statement and will always return true whether a substitution occurs or not. There is no action, which is equivalent to { print }, so each line is printed after being substituted.

But, better would be to use sed, just:

sed 's/Steven/Kate/' file

If you want to make the changes in place within the file, use

sed -i 's/Steven/Kate/' file

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