Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

shell - Succinct CSV complete file read using awk

I have a csv file with n different columns, an example is attached below. How can I output the entire csv file using an awk (to be used by a dbms using STDIN). I've tried

awk -v RS='
' '{print $1 ',' $1 + 1} file

but this wraps around causing the first column to also be printed at the end. Also is there a way to change the file ending when reading the csv so that it outputs in the form ' '. Preferably looking for a one-liner.

1, 20, Is
2, 12, this
3, 18, minimal
4, 21, enough

and the output should be

1, 20, Is
2, 12, this
3, 18, minimal
4, 21, enough

printed in terminal with line breaks and commas in the same position using awk (no cat).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm assuming you have some reason for doing this so....

Robustly with GNU awk for multi-char RS:

awk -v BINMODE=3 'BEGIN{RS=ORS="
"} 1' file

BINMODE (see https://www.gnu.org/software/gawk/manual/gawk.html#Built_002din-Variables) is required because on some platforms the underlying C primitives consume the line-ending s before gawk gets to see them.

idk how you'd deal with that BINMODE-requiring situation with a POSIX awk but if awk is seeing the s and assuming you don't have any s in the middle of your records (e.g. as you would when exporting a spreadsheet that includes cells that span multiple lines from MS-Excel) then in any awk:

awk '1' file

If you have fields that contain newlines and for more information generally on DOS line endings and parsing CSVs with awk see:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...