简体   繁体   English

awk函数打印... -bash?

[英]awk function printing… -bash?

For some reason that i'm trying to figure out i'm getting "-bash" printed out of this script: 由于某种原因,我试图弄清楚我从此脚本中打印的是“ -bash”:

cat sample | awk -v al=$0 -F"|" '{n = split(al, a, "|")} {print a[1]}'

the 'sample' file contains psv "pipe separated value", like a|b|c|d|e|f|d. “样本”文件包含psv“管道分隔值”,如a | b | c | d | e | f | d。
My intention is to use an array. 我的意图是使用数组。
The result of the above script is an array of length 1 and th only item contained is "-bash", the name of the shell. 上面脚本的结果是一个长度为1的数组,其中唯一包含的项是shell名称“ -bash”。
$0 by default points to the program that is currently used, but as far as i know, within an awk script, the $0 parameter 'should' point to the entire line being read. $ 0默认指向当前使用的程序,但是据我所知,在awk脚本中,$ 0参数“应该”指向正在读取的整行。

since i would like to understand where the problem exaclty is "i'm new to bash/awk" can you point me out which of the following steps is failing? 由于我想了解问题所在是“我是bash / awk的新手”,因此您可以指出以下哪些步骤失败了吗?
1-"concatenate" the sample file and pass it as input for the awk script 1-“串联”示例文件,并将其作为awk脚本的输入传递
2-define a variable named 'al' with as value each line contained in 'sample' 2-定义一个名为“ al”的变量,将“样本”中包含的每一行作为值
3-define a pipe "|" 3-定义管道“ |” as field separator 作为字段分隔符
4-define an action, split the value of 'al' into an array named 'a' using a pipe as splitter 4-定义一个动作,使用管道作为分隔符将'al'的值分割为名为'a'的数组
5-define another action, which in this case is simply printing the first item in the array 5-定义另一个动作,在这种情况下,它只是打印数组中的第一项

Any advice? 有什么建议吗? thank you! 谢谢!

The $0 is expanded by the shell before it runs awk , and $0 is the name of the current program, which is bash , the - at the start is because bash was run by login(1) (see the description of the exec builtin in man bash ) $0在运行awk之前由外壳程序进行了扩展,而$0是当前程序的名称,即bash-开头是因为bash是由login(1)运行的(请参阅内置的exec的说明man bash

You need to quote the $0 so the shell doesn't expand it, and awk sees it: 您需要引用$0这样外壳程序就不会对其进行扩展,而awk会看到它:

awk -v 'al=$0' -F"|" '{n = split(al, a, "|")} {print a[1]}' sample

But variable assignments are processed before reading any data, so that sets the variable al to the string "$0" at the start of the program, it does not set al to the contents of each input record. 但是读取任何数据之前先处理变量赋值,因此在程序启动时将变量al设置为字符串“ $ 0”, 而不al设置为每个输入记录的内容。

If you want the record, just say so instead of using a variable: 如果您想要记录,那么就这么说而不是使用变量:

awk -F"|" '{n = split($0, a, "|")} {print a[1]}' sample

By -v a1=$0 , you are setting a1 to the name of the current programme, which is bash. 通过-v a1=$0 ,您可以将a1设置为当前程序的名称,即bash。 See Arguments in man bash . 参见man bash中的 参数

呃...

awk -F'|' '{ print $1 }' sample

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

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