使用bash(SED / AWK)提取CSV文件中的行和列? [英] using bash (sed/awk) to extract rows AND columns in CSV files?
本文介绍了使用bash(SED / AWK)提取CSV文件中的行和列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
时的bash能够从CSV文件处理提取的行和列?希望我没有诉诸蟒蛇..
Is bash capable of handling extracting rows and columns from csv files? Hoping I don't have to resort to python..
我的5列csv文件如下:
My 5-column csv file looks like:
Rank,Name,School,Major,Year
1,John,Harvard,Computer Science,3
2,Bill,Yale,Political Science,4
3,Mark,Stanford,Biology,1
4,Jane,Princeton,Electrical Engineering,3
5,Alex,MIT,Management Economics,2
我只是想提取3日,4日,5日和列内容,忽略了第一排,所以输出如下:
I only want to extract the 3rd, 4th, and 5th column contents, ignoring the first row, so output looks like:
Harvard,Computer Science,3
Yale,Political Science,4
Stanford,Biology,1
Princeton,Electrical Engineering,3
MIT,Management Economics,2
到目前为止,我只能拿awk将打印出任何的每一行,还是我的CSV文件中的每一列,但像这种情况下,不特定COLS /行!可以来砸做到这一点?
So far I can only get awk to print out either each row, or each column of my CSV file, but not specific cols/rows like this case! Can bash do this?
推荐答案
猛砸解决方案;
使用IFS
#!/bin/bash
while IFS=',' read -r rank name school major year; do
echo -e "Rank\t: $rank\nName\t: $name\nSchool\t: $school\nMajor\t: $major\nYear\t: $year\n"
done < file.csv
IFS=$' \t\n'
使用字符串操作和阵列
#!/bin/bash
declare -a arr
while read -r line; do
arr=(${line//,/ })
printf "Rank\t: %s\nName\t: %s\nSchool\t: %s\nMajor\t: %s\nYear\t: %s\n" ${arr[@]}
done < file.csv
这篇关于使用bash(SED / AWK)提取CSV文件中的行和列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文