Delete last word in bash variable

I have something like this:

...
args=$*
echo $args
...

result

unusable1 unusable2 useful useful ... useful unusable3

I need to remove all unsuitable arguments. They are always in the first, second and last place. After some research, I find the ${*:3}bash syntax . This helps to remove the first two.

...
args=${*:3}
echo $args
...

result

useful useful ... useful unusable3

But I can not find how to remove the last word using the same beautiful syntax.

+4
source share
6 answers

args=${*:3}aligns a list of arguments. You do not want to do this. Consider the template below:

# this next line sets "$@" for testing purposes; you don't need it in real life
set -- \
  "first argument" \
  "second argument" \
  "third argument" \
  "fourth argument" \
  "fifth argument"

# trim the first two
args=( "${@:2}" )

# trim the last one
args=( "${args[@]:1:$(( ${#args[@]} - 2 ))}" )

# demonstrate the output content
printf '<%s>\n' "${args[@]}"

Execution of the above result gives the following result:

<third argument>
<fourth argument>

... and thus demonstrates that it stores arguments correctly together, even if they contain spaces or wildcards.


script :

printf '%q ' "${args[@]}"

..., , .

+2

/ script, , :

func() {
   echo "${@:1:$#-1}";
}

func aa bb cc dd ee
aa bb cc dd

func foo bar baz hello how are you
foo bar baz hello how are
+4

, :

args=${*:3:$#-3}

:

${*:offset:length}

- 3, , - 3 ( ).

+3

awk:

args="unusable1 unusable2 useful useful ... useful unusable3"
args=$(awk '{$1=$2=$NF="";print}' <<< "$args")
echo "$args"

:

  useful useful ... useful 

, ($NF) . NF awk. $NF - .

+1

bash . - .

for arg; do   # Implicitly iterate over $@
    [[ $arg =~ unusable ]] && continue
    args+=( "$arg" )
done
0

:

args=$*

useful=${args#* }
useful=${useful#* }
useful=${useful% *}

$result.

-1
source

Source: https://habr.com/ru/post/1540386/


All Articles