-3
$ 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?

chaos
  • 48,171

1 Answers1

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
ChrisDR
  • 487
chaos
  • 48,171