Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add "/" to end of line if it does not exist with sed

Tags:

bash

sed

I am trying to come up with a script to format forwards for apache, what I need to do is take a url, strip off the domain and then attach a "/" to the end of the line IF there is not one there already, now the script I have come up with is this:

#!/bin/bash
sed 's/http:\/\/www.mydomain.co.uk//g' address > address1

sed -e 's/$/\//' address1 > address2

now this script will take off the "http://www.mydomain.co.uk" at the begining and add a "/" at the end, but some of the url's I have already have the "/" there. how can I get sed to only add the "/" if its not already there?

like image 657
Andrew Cleveland Avatar asked Dec 08 '22 20:12

Andrew Cleveland


1 Answers

Match a character other than a slash at the end of the line and replace with the match (&) plus a slash:

sed 's![^/]$!&/!'

To make things a little easier, I changed the delimiter from / to !, so that the slashes in the find/replace parts don't need to be escaped.

like image 54
Tom Fenech Avatar answered Dec 14 '22 23:12

Tom Fenech