Sed: Difference between revisions

From Anthony Pastor Wiki Notes - Verba volant, scripta manent
Jump to navigation Jump to search
No edit summary
No edit summary
Line 31: Line 31:


=Extract from specific line to EOF=
=Extract from specific line to EOF=
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
sed -n '44519778,$p' input.log > output.log
sed -n '44519778,$p' input.log > output.log
Line 42: Line 43:


=Remove all leading blank lines at top of a file=
=Remove all leading blank lines at top of a file=
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
sed '/./,$!d'
sed '/./,$!d'
Line 47: Line 49:


=Comment out a file (# comment) from line 25 to end of file=
=Comment out a file (# comment) from line 25 to end of file=
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
sed '25,$s/^/#/'
sed '25,$s/^/#/'
Line 52: Line 55:


=To append a text after a specific pattern=
=To append a text after a specific pattern=
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
sed '/adImpressions=1/a bid_response_http_error_body=0'
sed '/adImpressions=1/a bid_response_http_error_body=0'
</syntaxhighlight>
=Insert line after first matching pattern=
sed '/CLIENTSCRIPT="foo"/a CLIENTSCRIPT2="hello"' input
<syntaxhighlight lang="bash">
</syntaxhighlight>
</syntaxhighlight>

Revision as of 17:35, 19 February 2016

Print a pattern between two (exclusive) words

echo "pattern" | sed -e 's/.*WORD1//' -e 's/WORD2.*$//'

Example:

$ ./ovh-api-bash-client.sh --url "/ip/45.102.38.141"
200 {"organisationId":null,"country":"fr","routedTo":{"serviceName":"ns612429.ip-45-102-38.eu"},"ip":"45.102.38.141/32","canBeTerminated":true,"type":"failover","description":null}

If we only want the routedTo information:

$ ./ovh-api-bash-client.sh --url "/ip/45.102.38.141" | sed -e 's/.*serviceName":"//' -e 's/"},"ip":.*$//'
ns612429.ip-45-102-38.eu

Delete pattern between two words

sed '/WORD1/,/WORD2/d' input

Replace pattern between two words

sed '/\[ssh-ddos\]/,/filter   = sshd-ddos/s/enabled  = false/enabled  = true/' /etc/fail2ban/jail.conf

Extract from specific line to EOF

sed -n '44519778,$p' input.log > output.log

Replace new lines with a comma and a space

sed -z 's/\n/, /'g my_file

Remove all leading blank lines at top of a file

sed '/./,$!d'

Comment out a file (# comment) from line 25 to end of file

sed '25,$s/^/#/'

To append a text after a specific pattern

sed '/adImpressions=1/a bid_response_http_error_body=0'

Insert line after first matching pattern

sed '/CLIENTSCRIPT="foo"/a CLIENTSCRIPT2="hello"' input