Skip to content
ELECTRONICS ENGINEERINGelectronics-engineering.com
Operating Systems

Examples of Using sed in Linux

print all the lines of a file except comments (they start with '#') cat $FILE | sed -e '/^#/d' print all the lines that start with a number cat $FILE…

https://www.electronics-engineering.com/en/examples-of-using-sed-in-linux/

Was this page useful? Rate it:
average 4.0 from 1 rating
Examples of Using sed in Linux

print all the lines of a file except comments (they start with ‘#’)

cat $FILE | sed -e '/^#/d'

print all the lines that start with a number

cat $FILE | sed -n "/^[0-9]/p"

print all the lines that do NOT start with a number

cat $FILE | sed -n "/^[0-9]/p"

remove all empty lines (made up only of n)

cat $FILE | sed -e "/^$/d"

remove all lines made up of spaces (and followed by n)

cat $FILE | sed -e "/^[ ][    ]*$/d"

remove all lines that contain ‘exportPIPPO’

sed "/export[ |       ]*PIPPO/d" $FILE

remove the path from a filename

echo "/usr/bin/prova" | sed -e "s/.*///"

prints: prova

print only the path

echo "/usr/bin/prova" | sed -e "s//[^/]*$//"

prints: /usr/bin

print the ‘n’th line of a file (in the example the 5th)

sed -n -e "5p" $FILE

– print some lines of a file (in the example from the 2nd to the 5th)

sed -n -e "2,5p" $FILE

examples of substitutions

sed "s/"/ /g"        .. sostituisce tutte le '"' con space
sed "s/,/ /g"         .. sostituisce tutte le ',' con space
sed 's:bin::'     .. sostituisce il primo 'bin' con nulla

examples of extractions

sed -n "/^uid=[0-9]*(([^)]*)).*/s//1/p"

extracts: the user’s name

- echo "-T100" | sed 's/^-T//'

extracts: 100

extracts the user and home fields (the 1st and the 6th) from the file /etc/passwd and formats them

cat /etc/passwd | sed 's/([^:]*):.*:(.*):[^:]*$/_dir=2 _user=1/'

prints: _dir=/ _user=root

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
1
0
Would love your thoughts, please comment.x
()
x