How to cut the last field from a shell string

前端 未结 5 902
孤独总比滥情好
孤独总比滥情好 2020-12-14 07:43

How to cut the last field in this shell string

LINE=\"/string/to/cut.txt\"

So that the string would look like this

LINE=\"/         


        
相关标签:
5条回答
  • 2020-12-14 08:14

    I think you could use the "dirname" command. It takes in input a file path, removes the filename part and returns the path. For example:

    $ dirname "/string/to/cut.txt"
    /string/to
    
    0 讨论(0)
  • 2020-12-14 08:15

    echo $LINE | grep -o '.*/' works too.

    0 讨论(0)
  • 2020-12-14 08:18

    For what it's worth, a cut-based solution:

    NEW_LINE="`echo "$LINE" | rev | cut -d/ -f2- | rev`/"
    
    0 讨论(0)
  • 2020-12-14 08:32

    This will work in modern Bourne versions such as Dash, BusyBox ash, etc., as well as descendents such as Bash, Korn shell and Z shell.

    LINE="/string/to/cut.txt"
    LINE=${LINE%/*}
    

    or to keep the final slash:

    LINE=${LINE%/*}/
    
    0 讨论(0)
  • 2020-12-14 08:35
    echo "/string/to/cut.txt" | awk -F'/' '{for (i=1; i<NF; i++) printf("%s/", $i)}'
    
    0 讨论(0)
提交回复
热议问题