What is the purpose of those special characters in the sed command? [closed] Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of What is the purpose of those special characters in the sed command? [closed] without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I found this bash command that creates a directory tree in your console window. I find it quite useful, but I don’t really understand how all of the special characters work. Could someone help break it down for me?

alias tree="ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^/]*//--/g' -e 's/^/   /' -e 's/-/|/'"

The first two are pretty simple to understand, this is creating an alias in bash that recursively lists the files and folders beneath the current directory.

1. alias tree="" 
2. ls -R

But after those I’m pretty much lost. I get that it’s piping the rest of the commands through grep and sed, but I don’t understand the rest of it or even what these modifiers are called.

Answer

alias tree="ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^/]*//--/g' -e 's/^/   /' -e 's/-/|/'"
  • ls -R: list subdirectories recursively
  • grep ":$": grep only for lines with : at the end of the line
  • sed -e 's/:$//': remove : at the end of the line
  • -e 's/[^-][^/]*//--/g': replace all path components except of last dir with --. To be precise replace any char except of - followed by any char except of / repeated zero or more times and then followed by /.
  • -e 's/^/ /': add 3 spaces at the beginning of the line
  • -e 's/-/|/': replace first - with |

There are many “problems” with this snippet starting with parsing of ls command, but leaving this aside, you can rewrite sed part in more compact way:

ls -R | grep ":$" | sed -e 's/:$//;s/[^-][^/]*//--/g;s/^/   /;s/-/|/'
We are here to answer your question about What is the purpose of those special characters in the sed command? [closed] - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji