Shell-Using sed to Remove Subdirectories from a List

I have a file like this:

$ cat file.txt
  /home/user/Directory1
  /home/user/Directory1/subdirectory1
  /home/user/Directory1/subdirectory2
  /home/user/Directory2

I want to get rid of any subdirectories. In other words, I want this to happen:

$ ./myprogram.sh
$ cat file.txt
  /home/user/Directory1
  /home/user/Directory2

I have tried reading in the first line and setting a string and then reading in each other line and using sed -i to remove the line if a substring of the new line the length of the first string matches. Anyway, it got unwieldy and did not work properly. Tell me if you want me to post the broken code here.

Also, the list is in alphabetical order, so that might or might not help.

Thank you so much!

Answers


Something like this:

cut -d / -f 1-4 file | uniq

Output:

/home/user/Directory1
/home/user/Directory2

Need Your Help

How to check whether Oracle instance is started using pfile or spfile?

database oracle

IS there a view where i can check whether an instance had been started using a pfile or an spfile?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.