[英]using bash (sed/awk) to extract rows AND columns in CSV files?
bash是否能够处理从csv文件中提取行和列? 希望我不必诉诸python ..
我的5列csv文件看起来像:
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列内容,忽略第一行,所以输出如下:
Harvard,Computer Science,3
Yale,Political Science,4
Stanford,Biology,1
Princeton,Electrical Engineering,3
MIT,Management Economics,2
到目前为止,我只能得到awk打印出我的CSV文件的每一行或每一列,但不是像这种情况那样打印特定的cols / rows! bash可以这样做吗?
awk -F, 'NR > 1 { print $3 "," $4 "," $5 }'
NR是当前行号,而$ 3,$ 4和$ 5是由给予-F的字符串分隔的字段
尝试这个:
tail -n+2 file.csv | cut --delimiter=, -f3-5
Bash解决方案;
使用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
使用cut
和tail
:
tail -n +2 file.txt | cut -d ',' -f 3-
sed 1d file.csv | while IFS=, read first second rest; do echo "$rest"; done
在这里,你去一个简单的AWK程序。
#!/usr/bin/awk -f
BEGIN {
# set field separator to comma to split CSV fields
FS = ","
}
# NR > 1 skips the first line
NR > 1 {
# print only the desired fields
printf("%s,%s,%s\n", $3, $4, $5)
}
perl -F, -lane 'if($.!=1){print join ",",@F[2,3,4];}' your_file
检查一下
这可能适合你(GNU sed):
sed -r '1d;s/([^,]*,){2}//' file
试试这个
awk -F, 'NR > 1 { OFS=",";print $3, $4, $5 }' temp.txt
或这个
sed -re '1d;s/^[0-9],\w+,//g' temp.txt
我已经为这种任务创建了包 - gumba如果你对coffeescript感到满意,你可以尝试一下
cat file.csv | tail -n +2 | \
gumba "words(',').take((words)-> words.last(3)).join(',')"`
grep '^,' outlook.contacts.csv | sed 's/^,\([^,]*\),[^,]*,\([^,]*\),.*/\1 \2/'
获取以a开头的所有行,
然后使用sed
替换带有第一个和第二个名称的空白字段。
粘贴后请注意某些原因将线路更改为此,以便您最好手动仔细操作。
grep '^,' outlook.contacts.csv | sed 's/^,([^,]),[^,],([^,]),./\1 \2/'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.