1

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?

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but when the argument list starts or ends with -k, this does not work.
@ramgorur I just added a quick fix for that. Let me know if that works for you.
1

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'`

2 Comments

Hi, sorry for not pointing out the outlier cases, there is a small subtlety, the question is updated. thanks!
but it does not work when the argument list begins with -k, I am novice at sed.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.