Linux Basics
Sed
Replace the first occurrence of a string in a file, and print the result
sed 's/find/replace/' filename
Replace all the occurrences of a string in a file, and print the result
sed 's/find/replace/g' filename
Replace all occurrences of an extended regular expression in a file
sed -E 's/regular_expression/replace/g' filename
Replace in place all the occurrences of a string in a file and overwrite the file
sed -i '' 's/find/replace/g' filename
Add prefix to all files
sed -i '1s/^/# Copyright (c) MIT License\n\n/' *
Replace only on lines matching the line pattern
sed '/line_pattern/s/find/replace/' filename
Print only text between n-th line till the next empty line:
sed -n 'line_number,/^$/p' filename
Apply multiple find-replace expressions to a file:
sed -e 's/find/replace/' -e 's/find/replace/' filename
Replace separator / by any other character not used in the find/replace patterns, e.g. ;
sed 's;find;replace;' filename
sed '\;deleteme;d' filename
Replacing Newlines with sed
sed ':a;N;$!ba;s/\n//g' filename
Delete the line at the specific line number in a file:
-
Any line number:
sed '<line_number>d' filename
-
First line:
sed '1d' filename
-
Last line:
sed '$d' filename
-
Multiple lines:
sed '1d;3d;5d' filename
-
Exclude lines:
sed '1,3!d' filename
-
Delete empty lines in a file:
sed '/^$/d’ filename