ramgorur
ramgorur

Reputation: 2164

Remove a substring from a bash variable

A bash variable contents are command line arguments, like this:

args="file-1.txt file-2.txt -k file-3.txt -k --some-argument-1 --some-argument-2"

the string -k can appear anywhere in the above string, there are some other arguments that are not -k.

Is it possible to extract all the strings (i.e. file names with all other arguments) except -k from the argument, and assign it to a bash variable?

Upvotes: 1

Views: 1648

Answers (3)

chepner
chepner

Reputation: 530940

Command-line arguments in bash should be stored in an array, to allow for arguments that contain characters that need to be quoted.

args=(file-1.txt file-2.txt -k file-3.txt -k --some-argument-1 --some-argument-2)

To extract strings other than -k, just use a for loop to filter them.

newargs=()
for arg in "${args[@]}"; do
    [[ $arg = "-k" ]] && newargs+=("$arg")
done

Upvotes: 1

John1024
John1024

Reputation: 113814

Using sed

Is is possible to extract all the strings (i.e. file names with all other arguments) except -k from the argument, and assign it to a bash variable?

I am taking that to mean that you want to remove -k while keeping everything else. If that is the case:

$ new=$(echo " $args " | sed -e 's/[[:space:]]-k[[:space:]]/ /g')
$ echo $new
file-1.txt file-2.txt file-3.txt --some-argument-1 --some-argument-2

Using only bash

This question is tagged with bash. Under bash, the use of sed is unnecessary:

$ new=" $args "
$ new=${new// -k / }
$ echo $new
file-1.txt file-2.txt file-3.txt --some-argument-1 --some-argument-2

Upvotes: 2

hrbrmstr
hrbrmstr

Reputation: 78792

Piping it to sed should work:

echo $args | sed -e 's/[[:space:]]\-[[:alnum:]\-]*//g'
file-1.txt file-2.txt file-3.txt

and you can assign it to a variable with:

newvar=`echo $args | sed -e 's/[[:space:]]\-[[:alnum:]\-]*//g'`

Upvotes: 1

Related Questions