A=44echo "ABCD" | awk -v GET_A=$A ’{print GET_A}’
说明:-v选项用于定义参数,这里表示将变量A的值赋予GET_A。
有多少个变量需要赋值,就需要多少个-v选项。与之等价的:应用于脚本中:
#! /bin/bash
sort -n filename |awk -F ':' '{print $1}'|uniq >id.txt
for id in `cat id.txt`; do
echo "[$id]"
awk -v id2=$id -F ':' '$1==id2 {print $2}' filename // 另外的方式为: awk -F ':' '$1=="'id'" {print $2}' filename
done
附件:
cat filename
1111111:13443253456
2222222:13211222122
1111111:13643543544
3333333:12341243123
2222222:12123123123
运行脚本后结果为:
[1111111]
13443253456
13643543544
[2222222]
13211222122
12123123123
[3333333]
12341243123
思路:
先创建一个后缀为 .sh 的文件,然后将内容,添加进入,并将其中failname改为你创建的 后缀为 .sh 的文件
然后去执行shell文件——>sh 加 文件,即可看到结果
[root@hf-01 awk]# awk 'gsub(/root/,"1111")' test.txt //把文件中所有的root替换为1111
1111x:0:0:1111:/1111:/bin/bash
operator:x:11:0:operator:/1111:/sbin/nologin
[root@hf-01 awk]# awk -F ':' 'gsub(/root/,"lll",$1) {print $0}' test.txt //把$1 中的root替换为lll
lllx 0 0 root /root /bin/bash
在不加-F ':' 指定分隔符,得到的结果不同
[root@hf-01 awk]# awk 'gsub(/root/,"AAA",$1) {print $0}' test.txt
AAAx:0:0:AAA:/AAA:/bin/bash
operator:x:11:0:operator:/AAA:/sbin/nologin
grep -E '123|abc' filename // 找出文件(filename)中包含123或者包含abc的行
egrep '123|abc' filename //用egrep同样可以实现
awk '/123|abc/' filename // awk 的实现方式
单引号
方法一:
[root@localhost ~]# head -3 |awk '{print "This is a '"'"'"$1}' test.txt //在前3行中,添加字符" This is a '
This is a 'root:x:0:0:root:/root:/bin/bash
This is a '&&&
This is a 'as***fsdf****
方法二
[root@localhost ~]# head -2 test.txt |awk '{print"11'\''" $1}' //在前2行中,添加字符11 '
11'root:x:0:0:root:/root:/bin/bash
11'&&&
双引号
[root@localhost ~]# head -2 test.txt |awk '{print"aaa\"" $1}' //在前2行中,添加字符aaa "
aaa"root:x:0:0:root:/root:/bin/bash
aaa"&&&
[root@localhost ~]# head -2 test.txt|sed 's/\(.*\)/11 '"'"'&/'g
11 'root:x:0:0:root:/root:/bin/bash
11 '&&&
[root@hf-01 ~]# cat 2.txt
a v c
1 f g
as 4 5a
dd && a.
1 2
[root@hf-01 ~]# cat 3.txt
aa a 6
13 f45
1 f fg
abc 6a2 asf 4fa
cda
abc
1
[root@hf-01 ~]# paste 2.txt 3.txt //将2和3文件中相同的行合并到一行
a v c aa a 6
1 f g 13 f45
as 4 5a 1 f fg
dd && a. abc 6a2 asf 4fa
1 2 cda
abc
1
[root@hf-01 ~]# paste -d '+' 2.txt 3.txt //把文件2和3合并到一行中,并用+ 号字符连接
a v c+aa a 6
1 f g+13 f45
as 4 5a+1 f fg
dd && a.+abc 6a2 asf 4fa
1 2+cda
+abc
+1
[root@hf-01 ~]#