$ 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
?
$ 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
?
If it must be with echo "Kate"
, use awk
:
echo "Kate" | awk 'NR==FNR{a=$0;next} sub("Steven", a, $0)1' - file
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.file
is processed and sub()
replaces Steven
with the value of a
.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