Search code examples
bashshellcut

Cut one word before delimiter - Bash


How do I use cut to get one word before the delimiter? For example, I have the line below in file.txt:

one two three four five: six seven

when I use the cut command below:

cat file.txt | cut -d ':' -f1

...then I get everything before the delimiter; i.e.:

one two three four five

...but I only want to get "five"

I do not want to use awk or the position, because the file changes all the time and the position of "five" can be anywhere. The only thing fixed is that five will have a ":" delimiter.

Thanks!


Solution

  • Pure bash:

    s='one two three four five: six seven'
    w=${s%%:*}                 # cut off everything from the first colon
    l=${w##* }                 # cut off everything until last space
    echo $l
    # => five
    

    (If you have one colon in your file, s=$(grep : file) should set up your initial variable)