Sed: Difference between revisions
From Leo's Notes
This page was last edited on 24 February 2017, at 04:21.
join every other line |
m Text replacement - "{{highlight|lang=bash" to "{{highlight|lang=terminal" |
||
| Line 45: | Line 45: | ||
== Join Every Other Line == | == Join Every Other Line == | ||
To join every other line, useful for making key:value pairs, use: | To join every other line, useful for making key:value pairs, use: | ||
{{highlight|lang= | {{highlight|lang=terminal|code= | ||
'$!N;s/\n/ /' | '$!N;s/\n/ /' | ||
}} | }} | ||
Revision as of 04:21, 24 February 2017
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
Simple search / replace
Global search and replace:
sed 's/<search>/<replace>/g'
To replace only the first match:
sed '0,/<search>/s//<replace>/'
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'
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.
Grap Specific Section using Regex
To grab a specific section of a string, for instance '3' in 'Server time offset: 3':
echo 'Server time offset: 3' | sed -n -e 's/.*: \([0-9]*\)/\1/p'
This can also be done with grep, though it isn't regex:
echo 'Server time offset: 3' | /bin/grep -ohE '[0-9]*'
Join Every Other Line
To join every other line, useful for making key:value pairs, use:
'$!N;s/\n/ /'