I have a file (a.txt) with the following content:

Redhat master 12345678 V1A 20.0/20.0.1
Windows slave 12345678 V1B 19.0/19.0.1

I want to grep line with the word "master" and replace the 4th and fifth field with a new value.

For example, a new a.txt might be:

Redhat master 12345678 V1B 20.0/20.0.2
Windows slave 12345678 V1B 19.0/19.0.1

Here "V1A" is replaced with "V1B" and "20.0/20.0.1" with "20.0/20.0.2"

Can someone help to achieve this?

I also want to pass new values as script parameter:

Can I pass new values as a parameter to a script? I was trying below script:

The contents of script (test.sh) is as follows:


if [ "$2" == "" ]; then
    echo usage: $0 \<version\> \<revision\>
    exit -1
awk '/master/{$4="$1";$5="$2"}' a.txt >newa.txt

When I run:

#bash test.sh V1B 20.0/20.0.2

it doesn't work.


With awk:

awk '/master/{$4="V1B";$5="20.0/20.0.2"};1' a.txt

First we search for lines with word "master" with /master/ and then replace the value on 4th ($4) and 5th ($5) field. Final 1 is just to print everything.


To pass new value as a parameter you need to use -v switch in awk, for example:

awk -v VAR1="$x" -v VAR2="$y" '/master/{$4=VAR1;$5=VAR2};1' a.txt

(though beware that it won't work properly if those variables contain backslashes).

  • Perfect! It works! – ganesh Jul 15 '15 at 11:01
  • -------------------------------------- – ganesh Jul 15 '15 at 11:11

in the line

 awk '/master/{$4="$1";$5="$2"}' a.txt >newa.txt

"$1" doesn't hold value passed from shell.

you should write

awk '/master/{$4="'$1'";$5="'$2'"}' a.txt > newa.txt

so that $1 frm calling shell is put in awk file.

  • Embedding external input as awk code is a bad idea. The best approach here is to use awk's ENVIRON array. (also note that you need to print those lines). – Stéphane Chazelas Oct 20 '15 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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