bash awk 在读取行中的行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20104364/
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 08:42:06  来源:igfitidea点击:

behavior of awk in read line

bashawk

提问by user2757300

 $ cat file
 11 asasaw121
 12 saasks122
 13 sasjaks22

 $ cat no
 while read line
 do
 var=$(awk '{print }' $line)
 echo $var
 done<file

 $ cat yes
 while read line
 do
 var=$(echo $line | awk '{print }')
 echo $var
 done<file

 $ sh no
 awk: can't open file 11
 source line number 1

 awk: can't open file 12
 source line number 1

 awk: can't open file 13
 source line number 1

 $ sh yes
 11
 12
 13

Why doesn't the first one work? What does awk expect to find in $1 in it? I think understanding this will help me avoid numerous scripting problems.

为什么第一个不起作用?awk 期望在 $1 中找到什么?我认为理解这将帮助我避免许多脚本问题。

回答by jkshah

awkalways expects a file name as input

awk总是期望一个文件名作为输入

In following, $lineis string not a file.

在下面,$line是字符串而不是文件。

 var=$(awk '{print }' $line)

You could say (Note double quotes around variable)

你可以说(注意变量周围的双引号)

 var=$(awk '{print }' <<<"$line")

回答by anubhava

Why doesn't the first one work?

Why doesn't the first one work?

Because of this line:

因为这一行:

var=$(awk '{print }' $line)

Which assumes $lineis a file.

假设$line是一个文件。

You can make it:

你可以做到:

var=$(echo "$line" | awk '{print }')

OR

或者

var=$(awk '{print }' <<< "$line")

回答by qwwqwwq

awk '{print }' $line
                 ^^ awk expects to see a file path or list of file paths here
                    what it is getting from you is the actual file line

What you want to do is pipe the line into awkas you do in your second example.

你想要做的是awk像你在第二个例子中所做的那样将这条线插入。

回答by Ed Morton

You got the answers to your specific questions but I'm not sure it's clear that you would never actually do any of the above.

你得到了你的具体问题的答案,但我不确定你是否真的不会做上述任何事情。

To print the first field from a file you'd either do this:

要从文件打印第一个字段,您可以执行以下操作:

while IFS= read -r first rest
do
    printf "%s\n" "$first"

done < file

or this:

或这个:

awk '{print }' file

or this:

或这个:

cut -d ' ' -f1 <file

The shell loop would NOT be recommended.

不推荐使用 shell 循环。