简体   繁体   English

如何在bash shell中格式化字符串?

[英]How to format a string in bash shell?

I am trying to format a variable in linux 我正在尝试在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. 不要在DOS或Windows上编辑bash脚本。 You can run dos2unix on the bash script. 您可以在bash脚本上运行dos2unix The issue is that Windows uses "\\r\\n" as a line separator, Linux uses "\\n". 问题是Windows使用“ \\ r \\ n”作为行分隔符,Linux使用“ \\ n”。 You can also manually remove the "\\r" characters in an editor on Linux. 您也可以在Linux上的编辑器中手动删除“ \\ r”字符。

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: 我有评论说它没有解决^ M,我实际上是这样做的:

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

After awk : awk之后:

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

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. 如果要在数字和分号之间输入回车符,则echo可能有问题,或者输入数据与您认为的不一样。 Perhaps you're editing your script on a Windows machine and copying it back, and your variable assignment is getting DOS-style newlines. 也许您正在Windows机器上编辑脚本并将其复制回去,并且变量分配正在获得DOS样式的换行符。 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 . 我会用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. printf的输出是可预测的,并且在不需要时可以像空白一样轻松清除掉垃圾。

Note the replacement of your cut . 请注意更换cut The functionality of bash built-ins is documented in the Bash man page under "Parameter Expansion", if you want to look it up. 如果您要查找bash内置函数,请在Bash手册页的“参数扩展”下进行记录。 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. 我在此处提供的替代功能与问题中所提供的功能不完全相同 ,但是在功能上与您提供的示例数据等效。

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

pattern matching is the way to go. 模式匹配是必经之路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM