我已经在shell脚本中定义了一个变量,我想使用它。由于某种原因,我无法将其传递到需要它的命令行中。
这是我的脚本,在最后几行失败
#! /usr//bin/tcsh -f
if ( $# != 2 ) then
echo "Usage: jump_sorter.sh <jump> <field to sort on>"
exit;
endif
set a = `cat $1 | tail -1` #prepares last row for check with loop
set b = $2 #this is the value last row will be checked for
set counter = 0
foreach i ($a)
if ($i == "$b") then
set bingo = $counter
echo "$bingo is the field to print from $a"
endif
set counter = `expr $counter + 1`
end
echo $bingo #this prints the correct value for using in the command below
cat $1 | awk '{print($bingo)}' | sort | uniq -c | sort -nr #but this doesn't work.
#when I use $9 instead of $bingo, it does work.
请问如何正确地将$ bingo传递到最后一行?
更新:按照Martin Tournoij接受的答案,处理命令中“ $”符号的正确方法是:
cat $1 | awk "{print("\$"$bingo)}" | sort | uniq -c | sort -nr
之所以不起作用,是因为变量仅在双引号("
)内而不是单引号('
)内被替换,并且你使用的是单引号:
cat $1 | awk '{print($bingo)}' | sort | uniq -c | sort -nr
以下应该工作:
cat $1 | awk "{print($bingo)}" | sort | uniq -c | sort -nr
你在这里也有一个错误:
#! /usr//bin/tcsh -f
应该是:
#!/usr/bin/tcsh -f
请注意,通常不建议使用csh编写脚本。它具有许多怪异之处,并且缺少一些功能(如功能)。除非确实需要使用csh,否则建议使用Bourne shell(/bin/sh
,bash,zsh)或脚本语言(Python,Ruby等)代替。
前两个示例中不必要使用cat。无需使用cat即可将文件重定向回awk。sort和uniq的处理也很可能在awk内完成,从而消除了与管道关联的效率低下的情况。
@RamanSailopal您能举个例子吗?
awk“ {print($ bingo)}” $ 1
在现代系统上,@ RamanSailopal几乎没有什么不同,除非您运行了数百次。