Sed: Difference between revisions
From Leo's Notes
This page was last edited on 9 February 2014, at 23:34.
No edit summary |
No edit summary |
||
| Line 22: | Line 22: | ||
Using the above tips, you can modify a file directly by using the <code>-i</code> parameter, with the filename as the second argument: | Using the above tips, you can modify a file directly by using the <code>-i</code> parameter, with the filename as the second argument: | ||
sed -i "search" /path/to/file | sed -i "search" /path/to/file | ||
== Inserting a Line Before/After a Match == | |||
Use: <code>0,/<regex>/s//<replacement text where \0 is the found line>/</code> | |||
# Add a password line before the first title entry in the grub.conf file. | |||
sed -i "0,/^title/s//password --encrypted $Password\n\n\0/" $GrubConfig | |||
To append after, just put \0 before your replacement text. | |||
[[Category:Linux]] | [[Category:Linux]] | ||
[[Category:TipsnTricks]] | [[Category:TipsnTricks]] | ||
[[Category:Code]] | [[Category:Code]] | ||
Revision as of 23:34, 9 February 2014
Simple search / replace
sed 's/<search>/<replace>/g'
Remove HTML tags
sed -e 's/<[^>]*>//g' <file>
Remove File Extensions
sed 's/\(.*\)\..*/\1/'
eg:
echo "house.txt" | sed 's/\(.*\)\..*/\1/' # returns 'house'
Delete Matching Line
sed '/someline/d'
Modifying a File Directly
Using the above tips, you can modify a file directly by using the -i parameter, with the filename as the second argument:
sed -i "search" /path/to/file
Inserting a Line Before/After a Match
Use: 0,/<regex>/s//<replacement text where \0 is the found line>/
# Add a password line before the first title entry in the grub.conf file. sed -i "0,/^title/s//password --encrypted $Password\n\n\0/" $GrubConfig
To append after, just put \0 before your replacement text.