代码段内容如下:
echo -n "Filename: "
read filename
echo -n "Data Fields? "
read -a ar
awk -F '[[:space:]][[:space:]]+' 'BEGIN{OFS = "--"} {for val in "${ar[@]}" printf $val }' $filename
ar是我正在读取的数组,文件名也是我正在读取的文件的名称。
文件如下:
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
我想做的是,接受用户的文件名,还获取他要显示的字段号,然后扫描文件并相应地产生输出。
数组“ ar”包含字段编号,例如1,2,3。
输入如下:
$ sh awk_prac.sh
Filename: employee.txt
Data Fields: 2 3
现在根据我在上面给出的输入,输出应如下所示:
Thomas Manager
Jason Developer
Sanjay Sysadmin
Nisha Manager
Randy DBA
但是每次我运行代码时,都会显示for之后的语法错误,指向“ val”。
awk: cmd. line:1: BEGIN{OFS = "--"} {for val in "${ar[@]}" printf $val }
awk: cmd. line:1: ^ syntax error
谁能指出错误。 #i_am_new_to_this#
答案 0 :(得分:0)
您问题下方的注释中说明了代码问题(awk不是shell),这是解决问题的方法:
$ cat tst.sh
echo -n "Filename: "
read filename
echo -n "Data Fields? "
read fields
awk -v fields="$fields" 'BEGIN{n=split(fields,f)} {for (i=1; i<=n; i++) printf "%s%s", $(f[i]), (i<n?OFS:ORS)}' "$filename"
$ ./tst.sh
Filename: file
Data Fields? 2 3
Thomas Manager
Jason Developer
Sanjay Sysadmin
Nisha Manager
Randy DBA