简体   繁体   English

awk打印在bash shell脚本中不起作用

[英]Awk print is not working inside bash shell script

When I use AWK print command outside shell it is working perfectly. 当我在shell外部使用AWK打印命令时,它工作得很好。 Below is content of the file (sample.txt) which is comma separated. 下面是以逗号分隔的文件(sample.txt)的内容。

IROG,1245,OUTO,OTUG,USUK

After, executing below command outside shell I get IROG as output. 之后,在shell外执行下面的命令我得到IROG作为输出。

cat sample.txt | awk -F, '{print $1}' > data.txt

Below is inside the shell script 下面是shell脚本

my $HOME        ='home/tmp/stephen';    
my $DATA        ="$HOME/data.txt";    
my $SAMPLE     ="$HOME/sample.txt";    
`cat $SAMPLE | awk -F, '{print $1}' > $DATA`;

But here i get the same content as in original file instead of 1st column. 但是在这里我得到的内容与原始文件相同,而不是第1列。

output is IROG,1245,OUTO,OTUG,USUK 输出是IROG,1245,OUTO,OTUG,USUK

but I expect only IROG . 但我希望只有IROG Can someone advise where I am wrong here? 有人可以告诉我这里错了吗?

The $1 inside your backticks expression is being expanded by perl before being executed by the shell. 你的反引号表达式中的$1在被shell执行之前被perl扩展。 Presumably it has no value, so your awk command is simply {print } , which prints the whole record. 据推测它没有任何价值,所以你的awk命令只是{print } ,它打印整个记录。 You should escape the $ to prevent this from happening: 你应该逃避$以防止这种情况发生:

`awk -F, '{print \$1}' "$SAMPLE" > "$DATA"`;

Note that I have quoted your variables and also removed your useless use of cat . 请注意,我引用了您的变量,并删除了您对cat的无用使用。

If you mean to use a shell script, as opposed to a perl one (which is what you've currently got), you can do this: 如果你想使用shell脚本,而不是perl脚本(这是你现在得到的),你可以这样做:

home=home/tmp/stephen
data="$home/data.txt"
sample="$home/sample.txt"
awk -F, '{print $1}' "$sample" > "$data"

In the shell, there must be no spaces in variable assignments. 在shell中,变量赋值中不能有空格。 Also, it is considered bad practice to use UPPERCASE variable names, as you risk overwriting the ones used internally by the shell. 此外,使用UPPERCASE变量名称被认为是不好的做法,因为您可能会覆盖shell内部使用的变量名称。 Furthermore, it is considered good practice to use double quotes around variable expansions to prevent problems related to word splitting and glob expansion. 此外,在变量扩展周围使用双引号来防止与单词拆分和全局扩展相关的问题被认为是一种好的做法。

There are a few ways that you could trim the leading whitespace from your first field. 您可以通过几种方法修剪第一个字段中的前导空格。 One would be to use sub to remove it: 一种方法是使用sub来删除它:

awk -F, '{sub(/^ */, ""); print $1}'

This removes any space characters from the start of the line. 这将从行的开头删除任何空格字符。 Again, remember to escape the $ if doing this within backticks in perl. 再次,如果在perl的反引号内执行此操作,请记住逃避$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM