0

For example

var="         |"

and

var2="hello"

How do I delete number of space characters that equals to the length of var2?

So var will now be " |" instead of " |"

I thought of doing something with ${#var2} minus var but I don't know how to delete specific characters.

0

4 Answers 4

2

Try

var=${var:${#var2}}

${var:${#var2}} expands to the characters in $var from index ${#var2} onwards. See Extracting parts of strings (BashFAQ/100 (How do I do string manipulation in bash?)).

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

Comments

2

Here's a fun one:

echo "${var/${var2//?/?}/}"
  • ${var2//?/?} replaces every character in $var2 with the character "?"
  • Then we use that string ("?????") as a pattern against $var, and we replace it with an empty string

Comments

0

You can remove one space at a time while the $var is longer:

#!/bin/bash
var="         |"
var2=hello
expect="    |"

while (( ${#var} > ${#var2} )) ; do
    var=${var#\ }
done

[[ $var = $expect ]] && echo Ok

or you can calculate the number of characters to remove and use the offset parameter expansion to skip them:

remove_length=$(( ${#var} - ${#var2} ))
var=${var:$remove_length}

Comments

0

Use parameter expansion:

#!/bin/bash

s1='      |'  # 6 spaces
s2='hello'    # 5 characters

(( to_remove=${#s2}+1 ))

echo "${s1:$to_remove}"  # 5 characters removed
# ' |'

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.