0

I would like to use awk to replace any occurrence of a given word with another word in a .sh The script I wrote is;

#!/bin/bash

read -p "Enter the word to change: "  wrd1
read -p "Enter the new word: "  wrd2
awk '{sub(/"$wrd1 /, $wrd2")}1' file.txt

but it's not working.

1 Answers1

0

Use the -v option.

awk -v w1="$wrd1" -v w2="$wrd2" '{sub(w1, w2)}1' file.txt

A demonstration:

$ awk -v w1="$wrd1" -v w2="$wrd2" '{sub(w1, w2)}1' <<EOF
foo=3
hi=9
bye=2
EOF

bar=3
hi=9
bye=2
chepner
  • 497,756
  • 71
  • 530
  • 681