How to Find the Last Field Using 'Cut'

How to find the last field using 'cut'

You could try something like this:

echo 'maps.google.com' | rev | cut -d'.' -f 1 | rev

Explanation

  • rev reverses "maps.google.com" to be moc.elgoog.spam
  • cut uses dot (ie '.') as the delimiter, and chooses the first field, which is moc
  • lastly, we reverse it again to get com

Cut first and last line field

This is an easy job for awk, get the first and last field:

awk '{print $1, $NF}' file.txt

To preserve the field separator:

awk 'BEGIN{OFS=FS} {print $1, $NF}' file.txt

How to get second last field from a cut command

Got a hint from Unix cut except last two tokens and able to figure out the answer :

cat datafile | rev | cut -d '/' -f 2 | rev

cut text file and get the last field following a delimeter

cut tells you what you have to do:

$ cut -d:
cut: you must specify a list of bytes, characters, or fields
Try 'cut --help' for more information.

So leave the second field.

cut -d: -f2

How to cut the last field from a shell string

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

How to split a string in shell and get the last field

You can use string operators:

$ foo=1:2:3:4:5
$ echo ${foo##*:}
5

This trims everything from the front until a ':', greedily.

${foo  <-- from variable foo
## <-- greedy front trim
* <-- matches anything
: <-- until the last ':'
}

How to cut till the last delimiter and get remaining part of a string

You can easily cut after the last delimiter, using awk, as you can see here:

cat conf.conf.txt | awk -F "/" '{ print $NF}'

(For your information: NF in awk stands for "Number of Fields".)

However, as the second line ends with a slash, the second result will be empty, as you see here:

test1

example

Is that what you want?



Related Topics



Leave a reply



Submit