Tom
Tom

Reputation: 2661

How to insert one character in front of a variable using sed

I want to turn this input_variable = 1 into input_variable = 01

From previous posts here I tried this but didn't work: sed -e "s/\0" <<< "$input_variable"

I get:

Syntax error: redirection unexpected

What do I do wrong?

Thanks!

EDIT Thanks to Benjamin I found a workaround (I would still like to know why the sed didn't work):

new_variable="0$input_variable"

Upvotes: 1

Views: 1318

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84561

While it can be done with sed, simple assignment in your script can do exactly what you want done. For example, if you have input_variable=1 and want input_variable=01, you can simply add a leading 0 by assignment:

input_variable="0${input_variable}"

or for additional types of numeric formatting you can use the printf -v option and take advantage of the format-specifiers provided by the printf function. For example:

printf -v input_variable "%02d" $input_variable

will zero-pad input_variable to a length of 2 (or any width you specify with the field-width modifier). You can also just add the leading zero regardless of the width with:

printf -v input_variable "0%s" $input_variable

sed is an excellent tool, but it isn't really the correct tool for this job.

Upvotes: 1

hgiesel
hgiesel

Reputation: 5648

You don't close the substitution command. Each substitution command must contain 3 delimiters

sed -e 's/pattern/replacement/' <<< 'text' # 3 backslashes

What you want to do could be done with:

sed -e 's/.*/0&/' <<< $input_variable

EDIT:

You are probably using Ubuntu and stumbled upon dash also known as the Almquist shell, which does not have the <<< redirection operator. The following would be a POSIX-compliant alternative, which works with dash as well:

sed -e 's/.*/0&/' <<~
$input_variable
~

And also this:

echo $input_variable | sed -e 's/.*/0&/'

To have the variable take on the new value, do this:

input_variable=$(echo $input_variable | sed -e 's/.*/0&/')

That's however not how you would write the shell script. Shell scripts usually give out some textual output, rather than setting external variables:

So, the script, let's call it append_zero.sh:

#!/bin/sh
echo $1 | sed 's/.*/0&/'

and you would execute it like this:

$ input_variable=1
$ input_variable=$(append_zero.sh input_variable)
$ echo $input_variable
01

This way you have a working shell script that you can reuse with any Unix system that has a POSIX compliant /bin/sh

Upvotes: 1

Related Questions