How to exclude or remove the word before the last word in line:
Example:
var=1
echo "list $var M"
Expected:
list 1M
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.
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