存档

文章标签 ‘shell’

awk使用shell中变量的方法

2011年9月3日 没有评论

awk中使用shell变量的方法有三种:

1、使用双引号quoting方法,就是在搜索的正则表达式的pattern中使用shell变量,这里可以直接使用双引号取得shell中的变量

     printf "Enter search pattern: "
     read pattern
     awk "/$pattern/" '{ nmatches++ }
          END { print nmatches, "found" }' /path/to/data

2、使用系统的环境变量:在awk中可以用ENVIRON数组引用系统的环境变量,例子如下

#!/bin/bash
id=1000
export id

awk '\
BEGIN {
    print ENVIRON["id"];
}' test.txt
运行之后输出:1000

3、使用awk assign方法,-v参数

在awk的手册中,-v参数的描述如下:

 -v var=val
       --assign var=val
       Assign the value val to the variable var, before execution of
       the program begins.Such variable values are  avail-able to
       the BEGIN block of an AWK program.

-v参数后面可以给某一个变量赋值,这个就是连接shell和awk中程序的桥梁,这个应该是传递shell中的变量到awk中的正统方法,推荐使用这个方法。

使用例子如下:

#!/bin/bash                                                                                                                         

id=1000

awk -v awkId="$id" '\
BEGIN {
    print awkId;
}' test.txt

输出:1000

参考文献:

http://yanwang.blog.51cto.com/1123232/383259

http://www.gnu.org/software/gawk/manual/html_node/Using-Shell-Variables.html

Popularity: 16%

分类: shell, unix 标签:

Shell判断文件,目录是否存在或者具有权限

2010年6月2日 1 条评论

#!/bin/sh

myPath=”/var/log/httpd/”
myFile=”/var /log/httpd/access.log”

#这里的-x 参数判断$myPath是否存在并且是否具有可执行权限
if [ ! -x "$myPath"]; then
mkdir “$myPath”
fi

#这里 的-d 参数判断$myPath是否存在
if [ ! -d "$myPath"]; then
mkdir “$myPath”
fi

#这里的-f参数判断$myFile是否存在
if [ ! -f "$myFile" ]; then
touch “$myFile”
fi

#其他参数还有-n,-n是判断一个变量是否是否有值
if [ ! -n "$myVar" ]; then
echo “$myVar is empty”
exit 0
fi

#两个变量判断是否相等
if [ "$var1" = "$var2" ]; then
echo ‘$var1 eq $var2′
else
echo ‘$var1 not eq $var2′
fi
原文链接:http://www.cublog.cn/u1/42339/showart_1355170.html

无觅相关文章插件

Popularity: 12%

分类: linux, shell, unix 标签: ,