0

I have a file with an argument

testArgument=

It could have something equal to it or nothing but I want to comment it and add the new line with supplied info

Before:

testArgument=Something

Results:

#testVariable=Something

#Comments to let the user know of why the change
testVariable=NewSomething

Should I loop it or should I use something like sed? I need it to be compatible for Ubuntu and Debian and bash.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
user3590149
  • 1,525
  • 7
  • 22
  • 25

2 Answers2

1

You could use sed like this:

sed 's/^\(testArgument\)=.*/#&\n\n#Comment here\n\1=NewSomething/' file

& prints the full match in the replacement and \1 refers to the first capture group "testArgument".

To perform the substitution on the file in-place (i.e. replace the contents of the original file), add the -i switch. Otherwise, if you want to output the command to a new file, do sed '...' file > newfile.

If you are using a different version of sed that doesn't support \n newlines in the replacement, see this answer for some ways to deal with it.

Alternatively, using GNU awk:

gawk '/^testArgument/ {$0 = gensub(/^(testArgument)=.*/, "#\\0\n\n#Comment here\n\\1=NewSomething", 1)}1' file
Community
  • 1
  • 1
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • What you mean by "file in-place"? I need to keep the same file because there is other data in the file. Does this make a new file? – user3590149 Sep 20 '14 at 15:37
  • Can I add additional requirement? Might make it harder. The 'testArgument' might be commented already so in that case then just add the new line under the that line. But if isn't commented then comment and add the new line afterwards. – user3590149 Sep 20 '14 at 18:08
  • O i mess this up. Theres no equals in my file after the argument. I guess I can rewrite your statement with this sed 's/^\(testArgument\).*/#&\n\n#Comment here\n\1 NewSomething/' file – user3590149 Sep 20 '14 at 18:39
  • That's probably because your version of seed doesn't support newline characters in the replacement string. The question I linked to explains how to deal with that. – Tom Fenech Sep 20 '14 at 18:44
  • If you got a chance, take a look at this question. http://stackoverflow.com/questions/25952293/bash-find-and-replace-with-new-lines-in-the-same-file Thanks for you help! – user3590149 Sep 20 '14 at 19:03
0

You can use awk

awk '/^testArugment/ {$0="#"$0"\n\n#Comments to let the user know of why the change\ntestVariable=NewSomething"}1' file

cat file
some data
testArugment=Something
more data

awk '/^testArugment/ {$0="#"$0"\n\n#Comments to let the user know of why the change\ntestVariable=NewSomething"}1' file
some data
#testArugment=Something

#Comments to let the user know of why the change
testVariable=NewSomething
more data

To change the original file

awk 'code....' file > tmp && mv tmp file
Jotne
  • 40,548
  • 12
  • 51
  • 55