Home > Enterprise >  how to delete letters from a string variable in bash?
how to delete letters from a string variable in bash?

Time:02-02

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.

CodePudding user response:

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?)).

CodePudding user response:

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

CodePudding user response:

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}

CodePudding user response:

Use parameter expansion:

#!/bin/bash

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

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

echo "${s1:$to_remove}"  # 5 characters removed
# ' |'
  •  Tags:  
  • bash
  • Related