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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28087461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:13:58  来源:igfitidea点击:

Awk print is not working inside bash shell script

bashshellunixawk

提问by stephenjacob

When I use AWK print command outside shell it is working perfectly. Below is content of the file (sample.txt) which is comma separated.

当我在 shell 外使用 AWK 打印命令时,它运行良好。以下是逗号分隔的文件 (sample.txt) 的内容。

IROG,1245,OUTO,OTUG,USUK

After, executing below command outside shell I get IROGas output.

之后,在 shell 外执行下面的命令,我得到IROG了输出。

cat sample.txt | awk -F, '{print }' > 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 }' > $DATA`;

But here i get the same content as in original file instead of 1st column.

但在这里我得到与原始文件相同的内容,而不是第一列。

output is IROG,1245,OUTO,OTUG,USUK

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

but I expect only IROG. Can someone advise where I am wrong here?

但我期望只有IROG. 有人可以建议我在这里错在哪里吗?

回答by Tom Fenech

The $1inside your backticks expression is being expanded by perl before being executed by the shell. Presumably it has no value, so your awk command is simply {print }, which prints the whole record. You should escape the $to prevent this from happening:

$1你的反引号内的表达是由Perl中被shell执行之前扩大。大概它没有价值,所以你的 awk 命令很简单{print },它会打印整个记录。您应该转义$以防止这种情况发生:

`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 }' "$sample" > "$data"

In the shell, there must be no spaces in variable assignments. Also, it is considered bad practice to use UPPERCASE variable names, as you risk overwriting the ones used internally by the shell. Furthermore, it is considered good practice to use double quotes around variable expansions to prevent problems related to word splitting and glob expansion.

在 shell 中,变量赋值中不能有空格。此外,使用 UPPERCASE 变量名被认为是不好的做法,因为您有覆盖 shell 内部使用的风险。此外,在变量扩展周围使用双引号被认为是一种很好的做法,以防止与分词和全局扩展相关的问题。

There are a few ways that you could trim the leading whitespace from your first field. One would be to use subto remove it:

有几种方法可以修剪第一个字段中的前导空格。一种是sub用来删除它:

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

This removes any space characters from the start of the line. Again, remember to escape the $if doing this within backticks in perl.

这将从行首删除任何空格字符。同样,记住$在 perl 的反引号内避免if 这样做。