How to format a string in bash shell?

2019-03-05 22:21发布

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;

标签: linux bash shell
4条回答
Rolldiameter
2楼-- · 2019-03-05 22:44

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.

查看更多
Rolldiameter
3楼-- · 2019-03-05 22:49

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.

查看更多
爷、活的狠高调
4楼-- · 2019-03-05 22:55

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$
查看更多
▲ chillily
5楼-- · 2019-03-05 23:09
str="Initial Value = 168"
newstr="${str##* }"
echo "$newstr"  # 168

pattern matching is the way to go.

查看更多
登录 后发表回答