在awk命令中使用Variable

时间:2016-09-20 07:33:02

标签: linux bash unix awk sh

我想在我的文本文件的每行末尾添加一个单词,该单词存储在变量中。每当我执行shell脚本而不是连接存储在变量变量中的内容时,都会连接起来。以下是相同的例子:

输入:

cat output2.txt

12345 

att1=Ramesh^Mumbai

awk '{print $0"^$att1"}' output2.txt >output3.txt

输出:

12345^att1

期望输出:

12345^Ramesh^Mumbai 

2 个答案:

答案 0 :(得分:0)

试试这个:

awk -v att1='Ramesh^Mumbai' -v OFS='^' '{print $0,att1}'

-v选项允许将变量传递给awk

OFS是输出字段分隔符(将,替换print语句中的^

答案 1 :(得分:0)

man awk:

-v var=val
Assign the value val to the variable var, before execution of
the program begins. Such variable values are available to the
BEGIN block of an AWK program.
你可以用这个;

#!/bin/bash
att1=Ramesh^Mumbai
awk -v att1=$att1 '{print $0"^"att1}' output.txt > output3.txt

实施例

user@host:/tmp$ cat output.txt
12345
abab
dafadf
adfaf

user@host:/tmp$, ./test.sh

user@host:/tmp$ cat output3.txt
12345^Ramesh^Mumbai
abab^Ramesh^Mumbai
dafadf^Ramesh^Mumbai
adfaf^Ramesh^Mumbai