sidman
sidman

Reputation: 213

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!

Upvotes: 2

Views: 18761

Answers (4)

Adi
Adi

Reputation: 505

you may want to do something like this:

cat file.txt | while read line
do
  for word in $line
    do
      if [ `echo $word | grep ':$'` ] then;
        echo $word
      fi
    done
done

if it is a consistent structure (with different number of words in line), you can change the first line to:

cat file.txt | cut -d':' -f1 | while read line
do ...

and that way to avoid processing ':' at the right side of the delimeter

Upvotes: 0

Ivan
Ivan

Reputation: 2320

Try

echo "one two three four five: six seven" | awk -F ':' '{print $1}' | awk '{print $NF}'

This will always print the last word before first : no matter what happens

Upvotes: -1

anubhava
anubhava

Reputation: 785156

Since you need to use more that one field delimiter here, awk comes to rescue:

s='one two three four five: six seven'
awk -F '[: ]' '{print $5}' <<< "$s"
five

EDIT: If your field positions can change then try this awk:

awk -F: '{sub(/.*[[:blank:]]/, "", $1); print $1}' <<< "$s"
five

Here is a BASH one-liner to get this in a single command:

[[ $s =~ ([^: ]+): ]] && echo "${BASH_REMATCH[1]}"
five

Upvotes: 2

Amadan
Amadan

Reputation: 198324

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)

Upvotes: 3

Related Questions