Replace String With Awk/Sed Command in Unix

  • Updated
  • Posted in Programming
  • 2 mins read


Replace String With Awk/Sed Command In Unix:

You might need used the Sed Command typically to switch the textual content in file. Awk may also be used to switch the strings in a file.

Here i’ll present you substitute the string with awk command. To study changing textual content with sed command go although the hyperlink, Replace String with Sed Command

Replace textual content with Awk command

1. First we are going to see a easy instance of changing the textual content. The supply file contians the beneath knowledge

>cat file.txt
Learn unix
Learn linux

We wish to substitute the phrase “unix” with “fedora”. Here the phrase “unix” is in the second subject. So, we have to examine for the phrase “unix” in the second subject and substitute it with workd “fedora” by assigning the brand new worth to the second subject. The awk command to switch the textual content is

awk '{if($2=="unix") {$2="fedora"} print $0}' file.txt
Learn fedora
Learn linux

2. Now we are going to see a bit advanced instance.Consider the textual content file with the beneath knowledge

>cat file.txt

left
(
In left
)
proper
(
In high
)
high
(
In high
)
backside
(
In backside
)

Now substitute the string, “high” in proper part with the string “proper”. The output ought to look as

left
(
In left
)
proper
(
In proper
)
high
(
In high
)
backside
(
In backside
)

Here the delimiter in the textual content file is brace. We must specify the delimiters in awk command with the file separators. The beneath awk command can be utilized to switch the string in a file

awk -vRS=")" '/proper/{ gsub(/high/,"proper"); }1' ORS=")" file.txt

Here RS is the enter file separator and ORS is the output file separator.

Recommended Posts:

Examples of Awk Command

If you want this publish, please share it on google by clicking the +1 button.

Leave a Reply