Text Processing with Sed and Grep: Powerful Command-Line Tools
sed
:
Basic Syntax:
sed OPTIONS 'COMMAND' FILE
Commonly Used sed
Commands:
Substitute:
s/old/new/
- Replace the first occurrence of "old" with "new" in each line.s/old/new/g
- Replace all occurrences of "old" with "new" in each line.
Delete:
d
- Delete the entire line./pattern/d
- Delete lines matching the specified pattern.
Print:
p
- Print the current line.
Insert and Append:
i\text
- Insert "text" before the current line.a\text
- Append "text" after the current line.
Address Ranges:
start, end COMMAND
- Apply the command to a range of lines from start to end.
Options:
-n
- Suppress automatic printing of pattern space.-e
- Specify multiple commands.
Examples:
Replace "hello" with "world" in a file:
sed 's/hello/world/' filename
Delete lines containing the word "error":
sed '/error/d' filename
Print only lines between line 5 and line 10:
sed -n '5,10p' filename
grep
:
Basic Syntax:
grep OPTIONS 'PATTERN' FILE
Commonly Used grep
Commands:
Search:
PATTERN
- Search for the specified pattern.
Options:
-i
- Ignore case (case-insensitive search).-v
- Invert the match.-r
- Recursively search directories.-l
- Only print the names of files with matching lines.-n
- Show line numbers.
Regular Expressions:
.
- Match any single character.*
- Match zero or more occurrences of the previous character or group.^
- Match the beginning of a line.$
- Match the end of a line.[]
- Match any character within the brackets.[0-9]
- Match any digit.[a-z]
- Match any lowercase letter.
Examples:
Search for the word "hello" in a file:
grep 'hello' filename
Search for the word "error" ignoring case:
grep -i 'error' filename
Recursively search for files containing "pattern" in a directory:
grep -r 'pattern' directory
Print only the names of files with lines matching the pattern:
grep -l 'pattern' *
Whether you're a beginner or an advanced user,
sed
and grep
can save you time and effort when working with text files. The commands and options covered in this cheatsheet provide a solid foundation for performing various text manipulation tasks.
However, both sed
and grep
have many more features to explore. Don't forget to consult their respective manuals (man sed
and man grep
) for more details and advanced usage.
Happy text processing!