Regex
'[condition(s)(optional)] [command/mode(optional)]/ [source/to-be-searched pattern(mandatory)]/ [to-be-replaced pattern(depends on command/mode you use)]/ [args/flags to operate on the pattern searched(optional)] '
sed 's/\(^\b[[:alpha:] ]*\)\([[:digit:]]*\)/\=\> \1\[\2\]/g' file.txt
Examples:
sed -e '1,3 s/john/JOHN/g' file.txt
Viewing a range of Lines:
sed -n '3,5p' file.txt
Viewing the entire file except a given range:
sed '3,5d' file.txt
Viewing multiple ranges of lines inside a file:
sed -n -e '1,2p' -e '4,5p' file.txt
To start searching from nth pattern occurrence in a line you can use combination of /g with /1,/2,/3.
sed 's/youtube/YOUTUBE/1' file.txt
İstenilen satırı aramak ve görüntülemek için:
sed -n '[line_number]p' [filename]
Kelimenin başına yazı eklemek veya değiştirmek için:
sed 's/^/[TEXT]:/g' [filename] > [output_filename]
Satırları silmek:
Belirli bir aralığı silmek için:
sed '[start_line_number],[end_line_number]d' [filename]
Belirli bir deseni içeren satırları silmek için:
sed '/[pattern]/d' [filename]
Aşağıda bulunan ilk komut belirtilen satırı ve sonrasındaki tüm satırları silerken, ikinci komut belirtilen satırı korur ve sonrasındaki tüm satırları siler.
Belirli bir satırdan sonraki tüm satırları silmek için:
sed '[start_line_number],$d' [filename]
Belirli bir satırdan başlayarak istediğiniz tüm satırları silmek için:
sed '[start_line_number],$!d' [filename]
Flags | Description |
---|---|
-e | To add a script/command that needs to be executed with the pattern/script(on searching for pattern) |
-f | Specify the file containing string pattern |
-E | Use extended regular expressions |
-n | Suppress the automatic printing or pattern spacing |
Command | Description |
---|---|
s | (Most used)Substitute mode (find and replace mode) |
y | Works same as substitution; the only difference is, it works on individual bytes in the string provided(this mode takes no arguments/conditions) |
Arguments | Description |
---|---|
/g | globally(any pattern change will be affected globally, i.e. throughout the text; generally works with s mode) |
/i | To make the pattern search case-insensitive(can be combined with other flags) |
/d | To delete the pattern found(Deletes the whole line; takes no parameter like conditions/modes/to-be-replaced string) |
/p | prints the matching pattern(a duplicate will occur in output if not suppressed with -n flag.) |
/1,/2,/3../n | To perform an operation on an nth occurrence in a line(works with s mode) |
Resources
- https://www.baeldung.com/linux/remove-last-n-lines-of-file
- https://unix.stackexchange.com/questions/323948/sed-explanation-sed-d-file
- Split 15 GB Text File in Windows. Split Large Text File
- https://www.geeksforgeeks.org/sed-command-in-linux-unix-with-examples/
- https://www.cyberciti.biz/faq/how-to-use-sed-to-find-and-replace-text-in-files-in-linux-unix-shell/
- https://www.tecmint.com/linux-sed-command-tips-tricks/
- Other