Hazin C.
Hazin C.

Reputation: 43

Bash saving a tr manipulated String

I have a small program that asks the user for its first name and last name. I need to change the last character of the given last name to an underscore(and any occurrence of it further in the String) in the first name and last name. Also I need to change the user its first name to uppercase letters. I got this part of the code where I manipulate the given strings.

echo -n "Hello "
X="$X" | tr ${Y:(-1)} "_"
echo -n "${X^^}"
echo " $Y" | tr ${Y:(-1)} "_"

for some reason line 2: X="$X" | tr ${Y:(-1)} "_" doesnt save the variable like I want it too. When I for instance fill "Cannon Nikkon" the program returns "Hello CANNON Nikko_". But when I print echo "$X" | tr ${Y:(-1)} "_" It prints "Hello Ca__o_ Nikko_". I tried to solve it with writing echo "${X^^}" | tr ${Y:(-1)} "_" instead but it still returned "Hello CANNON Nikko_". I figured out since n and N are not the same characters it won't change.

But why doesn't it save the variable in line 2? How do I need to approach this?

Upvotes: 1

Views: 241

Answers (2)

user2350426
user2350426

Reputation:

Use the correct tool to make changes in strings ${//}

first="jason";
echo "${first/%?/_}"     ### Using % means: "at the end of the string".

A full change will be:

first="jason";
first="${first/%?/_}"
first="${first^}"              ### Use ^^ to change all the string.
echo "$first"

And, asking the user will be:

#!/bin/bash
read -rp "Your first name, please: ? " first
read -rp "Your Last  name, please: ? " last
first="${first/%?/_}"
first="${first^}"
last="${last/%?/_}"
last="${last^}"
echo "$first $last"

Upvotes: 2

janos
janos

Reputation: 124714

If I understand correctly, instead of this:

X="$X" | tr ${Y:(-1)} "_"

You want to do this:

X=$(tr ${Y:(-1)} "_" <<< "$X")

That is, you want to write the output of tr back to X. The original statement didn't do that at all, it did something completely different:

  1. set the value of X to "$X"
  2. pipe the output of the assignment (nothing) to tr

The output of tr is printed, and it is not saved in X, contrary to what you may have believed.

Upvotes: 2

Related Questions