Sed Text Replace in Shell
Level 4101 keystrokes
sed is a stream editor. This code replaces text in file.txt in place, then prints the file, lines 2 to 5 only, and the file without the lines that contain "pattern". Here file.txt starts with six lines: "line 1: old_text data", "line 2: more data", "line 3: old_text again", "line 4: pattern here", "line 5: test" and "line 6: end".
Shell code
# s/old/new/g replaces every match; -i writes the result back to the file# GNU sed syntax; BSD/macOS sed needs -i ''1sed -i 's/old_text/new_text/g' file.txt# Show the edited file2cat file.txt# -n turns off automatic printing; 2,5p prints only lines 2 to 53sed -n '2,5p' file.txt# /pattern/d deletes lines containing "pattern" from the output (the file is unchanged)4sed '/pattern/d' file.txtOutput
line 1: new_text data line 2: more data line 3: new_text again line 4: pattern here line 5: test line 6: end line 2: more data line 3: new_text again line 4: pattern here line 5: test line 1: new_text data line 2: more data line 3: new_text again line 5: test line 6: end
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Shell code and how often they appear.
'× 6/× 5.× 4_× 2-× 2,× 1