Thursday, April 17, 2014

Linux command line notes/helpers

I just decided I need to start writing this stuff down and maybe it will help others. This is just stuff I tried to Google for, but found I didn't have the terms or people decided to post their own opinionated answers ("Well, you should..."). SED and then GREP + SED My search: Bash to find line and insert new multi-line (an if block in my actual use case) content after line in same file. Answer:
#!/bin/bash
sed -i '/search for me regex/a \
\
 new line1 with preceeding tab spacing \
 new line2 also with tab before just fyi \
 new line3 next line adds space after block \
\n' /path/to/file.txt

#end script. look at man sed for -i and /a.
Extended question: ...make sure change to file isn't already made. If it is made, then say so. If not, do change.
#!/bin/bash

if grep -Fq "new line1 with pre" /path/to/file.txt
 then 
  echo "This change is already applied."
 else
  echo "Writing to file..."
  sed -i '/search for me regex/a \
  \
   new line1 with preceeding tab spacing \
   new line2 also with tab before just fyi \
   new line3 next line adds space after block \
         \n' /path/to/file.txt
fi

#end script. look at man grep for the -F and the -q flags.

No comments: