1

I have some really simple questions which have bothered me all day:

  1. How can I get the first number in $variable?

  2. How can I remove the first number before ";"?

  3. How can I change the number with $updateNum?

$updateNum= 1

$variable="2;,A1,A2,A3,A4,A5,A6,A7,B1,B2,B3,B4,B5,B6,B7,C1,C2,C3,C4,C5,C6,C7,D1,D2,D3,D4,D5,D6,D7,E1,E2,E3,E4,E5,E6,E7,F1,F2,F3,F4,F5,F6,F7,G1,G2,G3,G4,G5"`

2 Answers 2

2

try:

oldVal="${variable%%;*}"
variable="$updateNum;${variable#*;}"
Sign up to request clarification or add additional context in comments.

1 Comment

0

This will do it all in one go:

variable=$(echo $variable | sed -E "s/[0-9]+?/$updateNum/")

Benchmark:

time variable=$(echo $variable | sed -E "s/[0-9]+?/$updateNum/") 

real    0m0.002s
user    0m0.001s
sys     0m0.000s 

5 Comments

using subprocesses slows down the execution, on one call - no big difference, on 20 calls you get into secconds
That is not a reason to downvote!? This solution for the given problem size is clear and easy to understand. Adding a comment to say 'doesn't scale well' is helpful but downvotes are for wrong answer, which this is not.
I do a lot shell scripting, and this is just a bad practice for me - counts for a downvote, this solution should be avoided unless you can justify it - which I can not.
To a beginner your solution looks very confusing i'm sure and you have offered no explanation (neither have I but i'm not the one downvoting) also alinsoar solution is an incomplete mess but you didn't downvote his? Are you sure the unjust downvote has nothing to do with the fact the OP accepted my answer?
sorry it has nothing to do with the fact of accepted answer, it's just a bad practice and shows lack of shell scripting knowledge, also @Shahbaz was kind enough to link to a description of all the "magic" which is just standard shell code

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.