Wednesday, February 2, 2022

[SOLVED] Delete Last String (Unix Shell Script)

Issue

I would like to delete the last string from a Linux/Unix variable containing multiple strings with space separation -

strings='Y NULL NULL NULL NULL NULL 20210607 NULL NULL NULL NULL NULL NULL EXCEL'

I want to delete the last string i.e. EXCEL

Expected Output -

Y NULL NULL NULL NULL NULL 20210607 NULL NULL NULL NULL NULL NULL

Other Input Set -

str1='RUB 20210607 SPREAD'
str2='RUSSIA NULL NULL NULL 20210607 Y Y Y N N Y Y HTML'
str3='LONDON NULL NULL NULL 20210607 Y Y Y N N Y Y CSV'

PS - Here string is trailing sequence of non-space characters.


Solution

The shell can remove or substritute leading or trailing patterns.

strings='Y NULL NULL NULL NULL NULL 20210607 NULL NULL NULL NULL NULL NULL EXCEL'
echo "${strings% *}"

prints

Y NULL NULL NULL NULL NULL 20210607 NULL NULL NULL NULL NULL NULL

You need the echo command only if you want to print the resulting value. Of course you can use ${strings% *} in the same way as you could use variable expansion, e.g. somecommand $strings vs. somecommand ${strings% *} or somecommand "$strings" vs. somecommand "${strings% *}", depending on your needs.

Citing https://pubs.opengroup.org/onlinepubs/009604499/utilities/xcu_chap02.html

${parameter%word}
Remove Smallest Suffix Pattern. The word shall be expanded to produce a pattern. The parameter expansion shall then result in parameter, with the smallest portion of the suffix matched by the pattern deleted.



Answered By - Bodo
Answer Checked By - David Marino (WPSolving Volunteer)