I am analyzing a text file looking for a path that is written after a line that starts with "output". The line is something like

output xyz/mypath/

and I want to extract xyz/mypath without the final slash.

On my Mac OS X (BSD) and Linux I get different behaviors when I get the path with this basepath=cat $basefile | grep -e ^output\ | cut -d" " -f2 | rev | sed 's@/$@@' | rev

The tricky part seems to be

sed 's@/$@@

which on Mac works, while it does not on Linux. Vice-versa if I do

sed 's@/@@ it works on linux not on Mac (BSD).

The trick seems to be related to the end-of-line char $ which is managed differently (maybe at the level of cat. Any suggestion to work around this in a way that both Mac and Linux console will do the job?

  • 1
    I don't get why you are reversing the string - surely that puts the / that you want to replace at the start of the line (anchor ^) rather than at $? Jun 11, 2014 at 11:22

3 Answers 3


I don't have easy access to an OSX machine but your approach is needlessly complex anyway. Just do something like these (depending on your actual input) instead:

basepath=$(grep ^output "$basefile" | awk '{print $NF}' | sed 's/[/]$//'


basepath=$(awk '/^output/{print $2}' "$basefile" | sed 's/[/]$//')

or even

basepath=$(grep -oP '^output\s+\K.+(?=/)' "$basefile")


basepath=$(perl -lne 'print $1 if /^output\s+(.+)\//' "$basefile";

That should work as is on Linux as far as I can tell - the sed statement at least - but if you want to know what's happening in sed's pattern space you should look at it:

sed 'l;s|/$||;l'

I think you could do the whole thing in sed like:

basepath=$(sed '/^output /!d;s|||;s|/$||' <"$basefile")

I'd suggest

sed -n '/^output / {s///; s,\(.*\)/,\1,p}'

which should work on GNU and OSX sed.

The empty regex in s/// re-uses the previous regex (/^output /)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .