Bash sed: Difference between revisions
Jump to navigation
Jump to search
(Created page with "==== Useful sed commands ==== cat foo | sed "1,/^stringMatch/d" * Will ignore all before string match until EOF * stringMatch must be start of line (^) Category:bash") |
|||
(6 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
==== Useful sed commands ==== | ==== Useful sed commands ==== | ||
== Ignore until EOF == | |||
<pre> | |||
cat foo | sed "1,/^stringMatch/d" | cat foo | sed "1,/^stringMatch/d" | ||
* Will ignore all before string match until EOF | * Will ignore all before string match until EOF | ||
* stringMatch must be start of line (^) | * stringMatch must be start of line (^) | ||
</pre> | |||
== Match all until EOF == | |||
<pre> | |||
cat foo | sed "/^stringMatch2/q" | grep -v "^stringMatch2" | |||
* will match ALL until match ( and remove match string LINE) | |||
</pre> | |||
== Strip pattern match == | |||
<pre> | |||
echo "192.168.15.58 172.17.0.1 123.10.130.201" | sed 's/172.[[:digit:]]\+.[[:digit:]]\+.[[:digit:]]\+//' | |||
192.168.15.58 123.10.130.201 | |||
</pre> | |||
* Will strip out IP addresses beginning with 172. | |||
== Replace in file only when matching regex == | |||
This will only alter values if the first arg matches | |||
Nice for changing values in a script or ini | |||
<pre> | |||
sed -ie '/^foo/s/4/20/g' /tmp/b | |||
cat /tmp/b | |||
foo=20 | |||
foo=4 | |||
bar=5 | |||
bar=5 | |||
</pre> | |||
== Strip leading and trailing whitespace == | |||
I like this a little better than the awk version which is shorter. However this makes sense in my head. | |||
<pre> | |||
| sed 's/^[[:blank:]]*//;s/[[:blank:]]*$//' | |||
</pre> | |||
[[Category:bash]] | [[Category:bash]] |
Latest revision as of 08:21, 17 October 2024
Useful sed commands
Ignore until EOF
cat foo | sed "1,/^stringMatch/d" * Will ignore all before string match until EOF * stringMatch must be start of line (^)
Match all until EOF
cat foo | sed "/^stringMatch2/q" | grep -v "^stringMatch2" * will match ALL until match ( and remove match string LINE)
Strip pattern match
echo "192.168.15.58 172.17.0.1 123.10.130.201" | sed 's/172.[[:digit:]]\+.[[:digit:]]\+.[[:digit:]]\+//' 192.168.15.58 123.10.130.201
- Will strip out IP addresses beginning with 172.
Replace in file only when matching regex
This will only alter values if the first arg matches Nice for changing values in a script or ini
sed -ie '/^foo/s/4/20/g' /tmp/b cat /tmp/b foo=20 foo=4 bar=5 bar=5
Strip leading and trailing whitespace
I like this a little better than the awk version which is shorter. However this makes sense in my head.
| sed 's/^[[:blank:]]*//;s/[[:blank:]]*$//'