Sed
search block between patterns
search between including pattern
sample.txt
some thing lkdsfj slkjdf ljfdlsjf
some thing BEGIN lkdsfj slkjdf END ljfdlsjf
some thing lkdsfj slkjdf ljfdlsjf
END
some thing lkdsfj slkjdf ljfdlsjf
The command below returns the lines between first occurrence of BEGIN
and first occurrence of END
in the next following lines. As you can you can observe in the line containing BEGIN
there is END, but this line is ignored. Hence the sed searches for the END
in the next line.
sed -n -e '/BEGIN/,/END/ p' sample.txt
output
some thing BEGIN lkdsfj slkjdf END ljfdlsjf
some thing lkdsfj slkjdf ljfdlsjf
END
search between excluding BEGIN pattern in the output
sed -n -e '/BEGIN/,/END/{ /BEGIN/! p}' sample.txt
replace with sed
replace newline with comma
Replace newline with comma and replaces the last comma at the end with newline
sed -z 's/\n/,/g;s/,$/\n/'
replace word in a file
sed -i '' -e 's/oldword/newword/g' <file-name>
replace a word in all files in a directory
grep -lr --exclude-dir=".git" -e "oldword" . | xargs sed -i '' -e 's/oldword/newword/g'