Ullan
Ullan

Reputation: 1007

How to format a string in bash shell?

I am trying to format a variable in linux

str="Initial Value = 168" 
echo "New Value=$(echo $str|  cut -d '=' -f2);">>test.txt

I am expecting the following output

Value = 168;

But instead get

Value = 168 ^M;

Upvotes: 2

Views: 21453

Answers (4)

David C. Rankin
David C. Rankin

Reputation: 84551

str="Initial Value = 168"
newstr="${str##* }"
echo "$newstr"  # 168

pattern matching is the way to go.

Upvotes: 2

Tiago Lopo
Tiago Lopo

Reputation: 7959

Try this:

#! /bin/bash

str="Initial Value = 168"

awk '{print $2"="$4}' <<< $str > test.txt

Output:

cat test.txt
Value=168

I've got comment saying that it doesn't address ^M, I actually does:

echo -e 'Initial Value = 168 \r' | cat -A 
Initial Value = 168 ^M$

After awk:

echo -e 'Initial Value = 168 \r' | awk '{print $2"="$4}' | cat -A
Value=168$

Upvotes: 1

ghoti
ghoti

Reputation: 46836

First off, always quote your variables.

#!/bin/bash

str="Initial Value = 168"
echo "New Value=$(echo "$str" | cut -d '=' -f2);"

For me, this results in the output:

New Value= 168;

If you're getting a carriage return between the digits and the semicolon, then something may be wrong with your echo, or perhaps your input data is not what you think it is. Perhaps you're editing your script on a Windows machine and copying it back, and your variable assignment is getting DOS-style newlines. From the information you've provided in your question, I can't tell.

At any rate I wouldn't do things this way. I'd use printf.

#!/bin/bash

str="Initial Value = 168"
value=${str##*=}
printf "New Value=%d;\n" "$value"

The output of printf is predictable, and it handily strips off gunk like whitespace when you don't want it.

Note the replacement of your cut. The functionality of bash built-ins is documented in the Bash man page under "Parameter Expansion", if you want to look it up. The replacement I've included here is not precisely the same functionality as what you've got in your question, but is functionally equivalent for the sample data you've provided.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

Don't edit your bash script on DOS or Windows. You can run dos2unix on the bash script. The issue is that Windows uses "\r\n" as a line separator, Linux uses "\n". You can also manually remove the "\r" characters in an editor on Linux.

Upvotes: 2

Related Questions