简体   繁体   English

在awk命令中使用FS和RS

[英]Using FS and RS in an awk command

I'm extremely new to Unix and have been looking into this issue for days. 我是Unix的新手,已经研究了好几天了。

I have the below set of information in a csv file that I need to manipulate through Unix. 我需要通过Unix处理的csv文件中包含以下信息集。

BEIGE ,   19.50 ,   STYLE ,   05/05/14
BEIGE ,   19.50 ,   STYLE ,   05/06/14
BEIGE ,   19.50 ,   STYLE ,   05/07/14

Using an awk command like below I am successfully grabbing the first field of the first line only; 使用如下的awk命令,我成功地仅捕获了第一行的第一个字段;

l_colour=$(awk 'BEGIN{FS=","} END {print $1}' file)

I need to store each field as a variable (l_colour, l_price, l_type, l_in_date) on line one, import into a database then do the same for line two and so on. 我需要在第一行中将每个字段存储为变量(l_colour,l_price,l_type,l_in_date),导入数据库,然后对第二行进行相同操作,依此类推。

Is it possible for me to use FS and RS in the same awk statement? 我可以在同一awk语句中使用FS和RS吗?

Please go easy on me. 请对我好一点。

Thanks, 谢谢,

I know this is not exactly answer to PO's question but inserting data from cvs to database could be done by something like this: 我知道这不能完全解决PO的问题,但是可以通过以下方式将数据从cvs插入数据库:

cat file | tr -s ' ' | sed 's/^\(.*\)$/INSERT INTO table(l_colour, l_price, l_type, l_in_date) VALUES(\1);/'

output : 输出:

INSERT INTO table(l_colour, l_price, l_type, l_in_date) VALUES(BEIGE , 19.50 , STYLE , 05/05/14);
INSERT INTO table(l_colour, l_price, l_type, l_in_date) VALUES(BEIGE , 19.50 , STYLE , 05/06/14);
INSERT INTO table(l_colour, l_price, l_type, l_in_date) VALUES(BEIGE , 19.50 , STYLE , 05/07/14);

It's not clear what you're hoping to get out of using awk for part of this. 目前尚不清楚您希望摆脱使用awk的部分功能。 For the input you posted you can just do: 对于您发布的输入,您可以执行以下操作:

$ while read -r l_colour c l_price c l_type c l_in_date
do
    echo "now insert \"$l_colour\", \"$l_price\", \"$l_type\", \"$l_in_date\""
done < file
now insert "BEIGE", "19.50", "STYLE", "05/05/14"
now insert "BEIGE", "19.50", "STYLE", "05/06/14"
now insert "BEIGE", "19.50", "STYLE", "05/07/14"

Change the echo line to whatever your database insertion command is. echo行更改为您的数据库插入命令。

If there's more to this question than you've told us so far, google how to store awk output in a bash array. 如果这个问题比您到目前为止告诉我们的更多,请使用google如何将awk输出存储在bash数组中。

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

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