Navigation

SED examples

sed '/^$/d' $file # remove empty lines
sed 's/replace/perpleaxed/g' # replace text
var=`echo "Hello\,World" | sed 's/\\\,/,/'`; echo $var --> "Hello,World" # remove backslash
sed -n 'H; /^CHECK/h; ${g;p;}' f1.txt # sed print from last occurrence match until the end of file
sed -n '/<pattern>/,$ p' <file> # from pattern to end of file
sed -n '/<pattern1>/,/<pattern2>/ p' <file> # from pattern1 to pattern2
sed -n '1,/<pattern>/ p' <file> # print from the first line until pattern is matched
sed '0,/RE/s//to_that/' file # sed script to change text only on the first occurrence

cat foo.c | sed '/^\s*$/d' | wc -l # count the number non-blank lines
cat foo.pl | sed '/^\s*#/d;/^\s*$/d' | wc -l # count the number non-blank lines
sed -n '/foo/{:a;N;/^\n/s/^\n//;/bar/{p;s/.*//;};ba};' # get all lines between first and last occurrences of patterns

http://unix.stackexchange.com/questions/47942/how-to-get-all-lines-betwe...
The sed pattern matching /first/,/second/ reads lines one by one. When some line matches to /first/ it remembers it and looks forward for the first match for the /second/ pattern. In the same time it applies all activities specified for that pattern. After that process starts again and again up to the end of file.
That's not that we need. We need to look up to the last matching of /second/ pattern. Therefore we build construction that looks just for the first entry /foo/. When found the cycle a starts. We add new line to the match buffer with N and check if it matches to the pattern /bar/. If it does, we just print it and clear the match buffer and janyway jump to the begin of cycle with ba.
Also we need to delete newline symbol after buffer clean up with /^\n/s/^\n//. I'm sure there is much better solution, unfortunately it didn't come to my mind.