How to assign a variable the sed command with formatting? Shellscript

Asked

Viewed 372 times

1

I’m having a problem making a program to exchange the first number for X, because even if it works, the variable does not receive the value permanently:

VAR="oi                                 200          20   10"
VAR= echo "$VAR" | sed -r -n "s/[0-9]+/X/p"
echo $VAR

It’s coming off:

oi                                 X          20   10
oi 200 20 10

I would like to know how to get the variable to permanently receive the exchange of the first number by X, and how to get the same formatting, because sed ignores the spaces I gave and puts only one in place. I wish the way out:

oi                                 X          20   10
oi                                 X          20   10
  • Related: https://answall.com/q/327578/112052

1 answer

1


To assign the result of a command to a variable has two options:

  • the first is to use backticks, ie the severe accent (`).
VAR=`echo "$VAR" | sed r -n "s/[0-9]+/X/p"`
  • the second would be to use the syntax $(comando)
VAR=$(echo "$VAR" | sed r -n "s/[0-9]+/X/p")

The second case is easier to read and allows you to nestle commands more easily, but that’s up to you. If you want more information, the name of this is command override.

To keep the formatting with the spaces between the numbers and the text, it is necessary to leave its variable between ". Therefore, the correct code would be

VAR="oi                                 200          20   10"
VAR=$(echo "$VAR" | sed -r -n "s/[0-9]+/X/p")
echo "$VAR"
  • Thank you! This worked as a question of assigning the variable, however the formatting is hi X 20 10, and should have all the spaces I initially put. You know how I can fix?

  • I updated the answer to be more complete (: but basically you need to leave your variable between double quotes to preserve the formatting

  • It worked in relation to formatting! But even printing all spaces, now it is without X instead of 200. You know how to solve?

  • I just ran the code I put there in the answer and X is in the right place. how’s your code? is with the $() and with the $VAR in quotes?

  • I did it! Thank you so much for your kindness and patience!!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.