Results 1 to 4 of 4

Thread: How to remove last part of the line with command?

  1. #1
    Join Date
    Mar 2007
    Beans
    680

    How to remove last part of the line with command?

    I got Windows file with file paths in it. I need to retain only directory structure and remove file names.

    Sample data in myfile.txt:
    Code:
    C:\aaa\bbbb\cccc\xxx.txt
    C:\aaa\bbbb\abc.txt
    C:\aaa\zzzz.txt
    <many hundreds of lines with different path depth>
    So in myfile.txt I need to search for the last backslash character "\" and remove everything to the end of line, to get:
    Code:
    C:\aaa\bbbb\cccc
    C:\aaa\bbbb
    C:\aaa
    How to remove file names from path?
    Thanks
    Last edited by abcuser; October 16th, 2012 at 01:42 PM.

  2. #2
    Join Date
    Sep 2006
    Beans
    8,627
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: How to remove last part of the line with command?

    I tried basename and dirname, but they did not work. However, sed does the job.

    Code:
    sed -e 's/\\[^\\]*$//' < myfile.txt > output.txt

  3. #3
    Join Date
    Oct 2010
    Location
    London
    Beans
    482
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: How to remove last part of the line with command?

    I think you'll have to use sed for this.

    Code:
    cat filename | sed 's\(.*\\\)/\1/' > outputfile
    will give you an output file with the xxx.txt removed, but it keeps the final backslash, I don't know how to remove that.

    EDIT: nevermind, ninja'd with a better solution

  4. #4
    Join Date
    Apr 2012
    Beans
    7,256

    Re: How to remove last part of the line with command?

    or you could use bash substitution

    Code:
    while read -r path; do echo "${path%\\*}"; done < myfile.txt

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •