-3

How to exclude or remove the word before the last word in line:

Example:

var=1
echo "list $var M"

Expected:

list 1M
Kalin Borisov
  • 1,091
  • 1
  • 12
  • 23

2 Answers2

2

Not sure what your problem is, but this:

var=1
echo "list $var M"

gives

list 1 M

To get list 1M, use this:

var=1
echo "list ${var}M"
list 1M

Using {...} makes sure the M is not part of the variable name.

Jotne
  • 40,548
  • 12
  • 51
  • 55
1

Since your question and expected answer is not matching, I am posting 2 answers.

1) To get output as indicated in question, 2) To remove 2nd last word

1. sed 's/ \(\w*$\)/\1/'

Check for last word (\w*$) with the preceding space. Replace the same, but without the space.

Output:

$ echo "list $var M" | sed 's/ \(\w*$\)/\1/'
list 1M

2. sed 's/\w* \(\w*$\)/\1/'

check for the last 2 words, replace with only the last word.

Output:

$ echo "list $var M" | sed 's/\w* \(\w*$\)/\1/'
list M
Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27