Stream Editor: sed

NAME
sed — stream editor

sed Useful Commands

Change the string something to else
sed 's/something/else/' [file]

Change the string something to else and add backup file:
Will output two files: one with the name file1.txt that contains the substitution, and the other with original content file1.txt.bu
sed -i.bu 's/something/else/' file1.txt

Rename a bunch of iPhone screenshot files from IMG_0001.PNG, IMG_0002.PNG…
to ScreenShot01.png, ScreenShot01.png…

for name in IMG*PNG
do
  # Work out the new name
  newname="$(echo $name | sed "s/IMG_00/ScreenShot/;s/PNG/png/")"

  # Move/rename the files
  echo "renaming $name as $newname"
  mv $name $newname
done

Link: https://ss64.com/osx/sed.html

Change Nth number of occurrence(s) of string:
replace only the second occurrence
sed 's/something/else/2' [file]

Change ALL occurrence(s) of string:
replace only the second occurrence
sed 's/something/else/g' [file]

Change string on Nth line number:
sed '[line] s/something/else/' [file]

Change string on line number 3:
sed '3 s/something/else/' [file]

Change string within line number range:
string replaced between lines 20 and 60
sed '20,60 s/something/else/g' [file]

Insert line breaks
sed G [file]

Remove lines from a file
Change n with number of lines to remove
sed 'nd' [file]

Display whole file except for X,Y range of lines:
shown everything except line 14 to 33
sed '14,33d' [file]

Show range of lines in file
sed -n 'Ni,Nlp' [file]

Display range of lines 4 to 14
sed -n '4,14p' [file]

Delete matching lines in file:
all lines with word something will be deleted.
sed '/something/d' [file]

Print line number in file
sed '=' [file]

Delete all lines except specified ones:
delete all lines except those from 14 to 33
sed '14,33!d' [file]

Replace all uppercase characters with lowercase
sed 's/\(.*\)/\L\1/' [file]

Remove line beginning with string
sed '/^something/d' [file]

Replace all occurrences of a string from X line to end
sed '[X Number Here],$s/macOS/Linux/g' [file]

Replace all occurrences something with else from line 9 to end of file
sed '9,$s/something/else/g' [file]

Print specific lines from file:
3 through 9 in following example
sed -n '3,9p' [file]

Remove blank lines after each line in file
sed '/^$/d'[file]

Capitalize first character of each word
sed 's/\([a-z]\)\([a-zA-Z0-9]*\)/\u\1\2/g'

Link:
Special Thanks Angelo
https://unixcop.com/top-20-sed-commands-to-use/#:~:text=The%20sed%20command%20is%20used%20to%20replace%20strings.,adapt%20the%20command%20by%20the%20strings%20you%20want.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Share via
Copy link