[colug-432] Tutorials

Jon Miller jonebird at gmail.com
Thu May 14 16:44:48 EDT 2015


Scott Merrill writes:

>> On May 14, 2015, at 2:45 PM, Steve VanSlyck <s.vanslyck at postpro.net> wrote:
>> 
>> I have a file,
>> 
>> /path/to/file_config
>> 
>> which is X lines long and one of the lines, location unknown, says,
>> 
>> Setting=No
>> 
>> What I want to do is write a simple bash script that will open that file, locate that line, change it to a comment, and then insert another line below it, with the end result looking like this:
>> 
>> # Setting=No
>> Setting=Yes
>> 
>> Imagine I am your willing but unlettered intern. You're willing to teach me but would prefer, obviously, that I teach myself. Always better that way.
>> 
>> Is there a tutorial that you would recommend?
>> 
>
> The script you’re looking to create is already written.  It’s a tool called sed.  sed is the “stream editor”.  You can pipe files into it, and it can spit out edited versions based on commands you define.
>
> sed is very  powerful.  The man page is likely not of particular help to you as you get started learning it.  Instead, I’d consult your favorite search engine for “sed tutorial” or similar, and work through a few of them.
>
> Another useful tool is awk.  awk is also powerful, but can feel like an arcane spell at times.
>
> Take your time learning both of these tools.  They’ll become indispensable for you as you grow more and more familiar with Linux!
>
> Cheers,
> Scott
>
>
>
> _______________________________________________
> colug-432 mailing list
> colug-432 at colug.net
> http://lists.colug.net/mailman/listinfo/colug-432

And while learning more on sed is helpful, here is the solution to get you
going:

1. Oneliner solution:
   sed '/^Setting=No/s/.*/# &\nSetting=Yes/g' configfile

2. Sed script solution:
   Put the following into a file called editfile.sed

/^Setting=No/ {
    s/.*/# &/g
    aSetting=Yes
}

   Then you could run: sed -f editfile.sed configfile

sed is good for these little in-line edits. When you are working out a sed
line, I tend to get it working first like above and when I then want to use
it to edit the file I'll then add the '-i' option that does an inplace edit
of the file.

Per testing, my typical pattern is:
- Test via:  sed -n '/^Setting=No/s/.*/# &\nSetting=Yes/p' configfile
- Real edit: sed -i '/^Setting=No/s/.*/# &\nSetting=Yes/g' configfile

-- 
Jon Miller


More information about the colug-432 mailing list