0

How do I use awk command to make permanent modifications to a file? I have been using:

awk '/'"'"'test'"'"' =>./{c++}(c==2){sub("'"'"'test'"'"' =>.","'"'"'test'"'"' => '"'"'test1'"'"',")}1' testfile

I have been using the above command to make temporary changes that open the changes instantly. But I want to use it within the script file and make permanent changes to the file similar to sed -i.

Joaquin
  • 2,013
  • 3
  • 14
  • 26
  • I looked at it already. The responses were not accurate with respect to the question. – Ragavendar balaji Jul 22 '18 at 17:48
  • 1
    Regardless of the details of the Q, the first 2 answers have all you need to know about saving files inplace while using `awk`. When you search for `[awk] inplace`, there are 242 Q/A already. So this is a duplicate Q. Please read [help] before posting more Qs here. Good luck. – shellter Jul 22 '18 at 19:11

1 Answers1

3

Before this gets closed as a dup, lets at least clean up your code. This:

awk '/'"'"'test'"'"' =>./{c++}(c==2){sub("'"'"'test'"'"' =>.","'"'"'test'"'"' => '"'"'test1'"'"',")}1' testfile

is extremely hard to read. I assume all those '"'"'s are trying to get single quotes into the code. If so, to improve clarity and so it'd work if/when the script is stored in a file, use the octal representation \047 for every single quote instead:

awk '/\047test\047 =>./{c++} (c==2){sub("\047test\047 =>.","\047test\047 => \047test1\047,")}1' testfile

Now use regexp delimiters for the regexp that's the first arg to sub():

awk '/\047test\047 =>./{c++} (c==2){sub(/\047test\047 =>./,"\047test\047 => \047test1\047,")}1' testfile

There are several other possible improvements including using a backreference instead of hard-coding the original sub() string in the replacement and using match() so you don't need to test for the same regexp in the condition part of the script and then again in the sub() so something like this (with GNU awk for the 3rd arg to match()) is probably all you need:

awk 'match($0,/(.*\047test\047 =>.)(.*)/,a){c++} c==2{$0=a[1] "\047test1\047" a[2]} 1' testfile

but without sample input output we can't know for sure - post a new question with sample input/output if you'd like more help.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185