0

I have a bash script to control Linux perf. As you may know, perf takes core list which can be specified in 1 of the three ways.

  1. -C1 #core 1 only
  2. -C1-4 # core 1 through 4
  3. -C1,3 # core 1 and 3

Currently, I have an environment variable CORENO which will control -C$CORENO.

However, I need to offset CORENO by a fix offset (I.e.2)

I could do ((CORENO+=2)) but that only work for case 1.

Is there a Linux/bash trick to allow me to apply fix offset to every number in a bash variable?

3 Answers 3

2

Since you're on Linux, here's some GNU sed:

addtwo() {
  sed -re 's/[^0-9,-]//g; s/[0-9]+/$((\0+2))/g; s/^/echo /e;' <<< "$1"
}

addtwo "1"
addtwo "1-4"
addtwo "3,4,5"

It will output:

3
3-6
5,6,7

It works by replacing all numbers with $((number+2)) and evaluating the result as a shell command. A whitelisting of allowed characters is applied first to avoid any security issues.

Sign up to request clarification or add additional context in comments.

1 Comment

This gives me another practical example of using sed!
1

Take a look at seq

for core in `seq 2 10`; do
  echo CORENO=$core
done

Comments

1

I’ve upvoted the sed-based answer from @that other guy because I like it more than mine, which is a “pure bash” solution, consisting of a recursive function.

function increment () {
    local current="$1" n=$(($2))
    if [[ "$current" =~ ^[0-9]+$ ]]; then
        echo $((current+n))
    elif [[ $current == *,* ]]; then
        echo $(increment ${current%%,*} $n),$(increment ${current#*,} $n)
    elif [[ $current == *-*-* ]]; then
        echo ERROR
    elif [[ $current == *-* ]]; then
        echo $(increment ${current%-*} $n)-$(increment ${current#*-} $n)
    else
        echo ERROR
    fi
}

CORENO=3-5
CORENO=$(increment $CORENO 2)
echo $CORENO

increment 3-5,6-8 3

My function will print ERROR when given an illegal argument. The one from @that other guy is much more liberal...

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.