3

I'm trying to output my $PATH in the command line, but also replace the : with \n using the following:

echo $PATH | sed s/:/\n/g

This doesn't work 100%, how to I get it working?

4
  • 3
    why sed ? doesn't tr ':' '\n' work ?
    – BatchyX
    Mar 7, 2013 at 10:10
  • I don't understand your comment? Mar 7, 2013 at 10:12
  • Use More Quotes™: echo "$PATH" | sed 's/:/\n/g'
    – l0b0
    Mar 7, 2013 at 14:05
  • The simplest solution is to use a bash substitution: echo "${PATH//:/$'\n'}" Oct 22, 2018 at 1:07

2 Answers 2

5

You need to escape the backslash, i.e.

echo $PATH | sed s/:/\\n/g

Or, as BatchyX noted

echo $PATH | tr ':' '\n'

Another possibility, if you want to parse $PATH, you can also use

IFS=:
for i in $PATH; do
   echo $i
done

Here IFS=: tells bash to split strings at :. Please note, that this will alter other things in the current session, too. Excerpt from man bash:

IFS The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is <space><tab><newline>

11
  • Doesn't the : need to be backslashed as well?
    – pratnala
    Mar 7, 2013 at 10:22
  • @pratnala: Don't think so... I tested the command successfully in bash and zsh.
    – mpy
    Mar 7, 2013 at 10:25
  • When I run your first example in the cmd line, the colons are replaced, but with a literal \n, so my path isn't getting split to newlines at the colons. Mar 7, 2013 at 10:34
  • 1
    @mpy I don't think you have to escape the backslash because \n as a whole represents the return character, isn't it? Escaping the backslash makes '\' and 'n' two separate characters
    – pratnala
    Mar 7, 2013 at 10:52
  • 1
    You need to escape the \ because the sed pattern is not quoted. A more robust method would be @user1936123 answer below.
    – terdon
    Mar 7, 2013 at 11:12
4

You could also quote the regular expression:

echo $PATH | sed 's/:/\n/g'

For your \n literals, you could use echo -e.

1
  • @josef.van.niekerk: Does that command work for you? (I would assume it's identical to my first one -- \n gets passed directly to sed)
    – mpy
    Mar 7, 2013 at 11:14

You must log in to answer this question.

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