bash - 使用 cut 的奇怪 bash 结果

标签 bash ubuntu cut

我正在尝试运行此命令:

./smstocurl SLASH2.911325850268888.911325850268896
smstocurl脚本:
#SLASH2.911325850268888.911325850268896
model=$(echo \&model=$1 | cut -d'.' -f 1)
echo $model
imea1=$(echo \&simImea1=$1 | cut -d'.' -f 2)
echo $imea1
imea2=$(echo \&simImea2=$1 | cut -d'.' -f 3)
echo $imea2
echo $model$imea1$imea2

收到结果
&model=SLASH2911325850268888911325850268896

预期结果
&model=SLASH2&simImea1=911325850268888&simImea2=911325850268896

我在这里想念什么?

最佳答案

你是 cut ting 基于点 . .在第一种情况下,您想要的字符串包含第一个字符串,即包含 &model 的字符串。 ,所以它被打印出来。

但是,在其他情况下,您将获得第二和第三 block ( -f2-f3 ),因此 imea文本被截断。

相反,我会使用这样的东西:

while IFS="." read -r model imea1 imea2
do
    printf "&model=%s&simImea1=%s&simImea2=%s\n" $model $imea1 $imea2
done <<< "$1"

注意 printf 的用法和变量来更好地控制我们正在编写的内容。在你的 echo 中使用很多转义符s 可能有风险。

测试
while IFS="." read -r model imea1 imea2; do printf "&model=%s&simImea1=%s&simImea2=%s\n" $model $imea1 $imea2
done <<< "SLASH2.911325850268888.911325850268896"

返回:
&model=SLASH2&simImea1=911325850268888&simImea2=911325850268896

或者,这个 sed使它:
sed -r 's/^([^.]*)\.([^.]*)\.([^.]*)$/\&model=\1\&simImea1=\2\&simImea2=\3/' <<< "$1"

通过捕获由点分隔的每个单词 block 并打印回来。

关于bash - 使用 cut 的奇怪 bash 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26713093/

相关文章:

c++ - 将命令行参数传递给从 C++ 程序调用的 bash shell 脚本

ruby - 在一条线上搜索和标记成对模式

linux - Netbeans 菜单在 Ubuntu 中很糟糕——完全不可读而且看起来很糟糕。任何修复?

Bash:如何在使用 cut 之前修剪空格

regex - 如何在 bash 中将空白字符与正则表达式匹配?

从c文件调用rrd_create

直接在 Ubuntu 14.04 中运行 JGR for R

linux - 如何使用 cut 为分隔符指定更多空格?

bash - 剪切/格式化docker服务命令

python - 为什么 bash (WSL) 使用 w3m 作为默认浏览器?