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;
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;
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.First off, always quote your variables.
For me, this results in the output:
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
.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.Try this:
Output:
I've got comment saying that it doesn't address ^M, I actually does:
After
awk
:pattern matching is the way to go.