bash:变量名后面跟着其他参数?

时间:2011-06-29 10:32:28

标签: bash variables

我的bash脚本有一个变量$c,在sed行内调用,后面跟着另一个参数 - 而bash(实际上相当合乎逻辑)似乎在想其他参数属于变量名称,使其无用/空。

(...)
c=$(printf "%02d" $(echo "$i+1"|bc))
sed -n "$cq;d" /var/www/playlisten.txt|cut -c 4-
(...)

第一行设置临时变量,然后将其作为sed参数调用。我需要显示b $c在c之后结束并且该变量未命名为$cq(当然是空的)...

任何想法都将一如既往地受到高度赞赏。

谢谢, 基督教。

PS。我正在努力实现的目标:)这是一个循环,步骤通过00..50,在循环内数字本身是需要的,但也是数字+1。以防万一有人想知道。

3 个答案:

答案 0 :(得分:8)

您需要使用${c}q来阻止贪婪的处理(bash尝试使用尽可能多的有效字符):

pax$ export cq=111

pax$ export c=222

pax$ echo $cq
111

pax$ echo ${c}q
222q

我还应该提一下,如果性能对您很重要,您希望尽量减少运行多少外部进程(如bc)来完成任务。分叉和执行不是免费的操作,如果你让bash为短期任务完成大部分工作,你的运行速度会快得多。

短暂的意思是指向变量添加一个。显然,如果你想在sed整个文件中执行工作,那么最好在专用的外部工具中执行此操作,但bash提供了相当大的功能替换昂贵的操作,如i=$(expr $i + 1)i=$(echo "$i+1"|bc)

可以完成bash循环,无需外部过程即可处理增量和其他计算:

#!/bin/bash
for ((count = 0; count < 10; count++)) ; do
    ((next = count + 1))
    echo "count is ${count}, sed string is '${next}q;d'."
done

输出:

count is 0, sed string is '1q;d'.
count is 1, sed string is '2q;d'.
count is 2, sed string is '3q;d'.
count is 3, sed string is '4q;d'.
count is 4, sed string is '5q;d'.
count is 5, sed string is '6q;d'.
count is 6, sed string is '7q;d'.
count is 7, sed string is '8q;d'.
count is 8, sed string is '9q;d'.
count is 9, sed string is '10q;d'.

您还可以将next合并到for循环中:

#!/bin/bash
for ((count = 0, next = 1; count < 10; count++, next++)) ; do
    echo "count is ${count}, sed string is '${next}q;d'."
done

答案 1 :(得分:2)

将变量名称放在大括号中:

c=$(printf "%02d" $(echo "$i+1"|bc))
sed -n "${c}q;d" /var/www/playlisten.txt|cut -c 4-

答案 2 :(得分:2)

稍短

sed -n "$(printf "%02d" $((i+1)))q;d" /var/www/playlisten.txt|cut -c 4-