如果我有以下格式的csv文件:
column1,column2,column3,column4,column5,column6,column7,column8我希望awk只打印第2列直到第7列,我将使用:
awk -F',' '{print $2 "," $3 "," $4 "," $5 "," $6 "," $7}' file.csv并得到:
column2,column3,column4,column5,column6,column7是否有方法连接列2-7以简化命令。当我想到一个列更多的文件时,我的awk命令会变得非常长。
发布于 2019-07-29 13:56:19
$ awk -v b=2 -v e=7 'BEGIN{FS=OFS=","} {for (i=b;i<=e;i++) printf "%s%s", $i, (ib=beginning字段号,e=end字段号。如果您需要处理带有引号字段、嵌入逗号、换行符等的CSV,请参见https://stackoverflow.com/q/45420535/1745001。
发布于 2019-07-28 16:32:19
实用程序裁剪有一个紧凑的符号:
cut -d, -f2-7 制作:
column2,column3,column4,column5,column6,column7
回答@PlasmaBinturong的评论:我的意图是解决一个简短的呼叫序列问题:“.我的awk命令会变得非常长……”。然而,你也可以找到代码来排列你可能想要的字段。尽管我非常喜欢awk、perl、python,但我常常发现构建一个特定的实用程序来扩展标准*nix的功能非常有用。下面是一个测试脚本s2的摘录,显示实用程序重排和排列,两者都允许重新排列和复制,而OR排表也允许减少字段范围:
FILE=${1-data1}
# Utility functions: print-as-echo, print-line-with-visual-space.
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
pl " Input data file $FILE:"
head $FILE
pl " Results, cut:"
cut -d, -f2-7 $FILE
pl " Results, recut (modified as my-recut):"
my-recut -d "," 7,6,2-5 < $FILE
pl " Results, arrange:"
arrange -s "," -f 5,3-1,7,5,3-4,5 $FILE产生这些版本的结果:
OS, ker|rel, machine: Linux, 3.16.0-10-amd64, x86_64
Distribution : Debian 8.11 (jessie)
bash GNU bash 4.3.30
cut (GNU coreutils) 8.23
recut - ( local: RepRev 1.1, ~/bin/recut, 2010-06-10 )
arrange (local) 1.15
-----
Input data file data1:
column1,column2,column3,column4,column5,column6,column7,column8
-----
Results, cut:
column2,column3,column4,column5,column6,column7
-----
Results, recut (modified as my-recut):
column7,column6,column2,column3,column4,column5
-----
Results, arrange:
column5,column3,column2,column1,column7,column5,column3,column4,column5my-recut是对文本代码重排的轻微修改,而排列是我们版本的扩展裁剪。更多信息:
recut Process fields like cut, allow repetitions and re-ordering. (what)
Path : ~/bin/recut
Version : - ( local: RepRev 1.1, ~/bin/recut, 2010-06-10 )
Length : 56 lines
Type : Perl script, ASCII text executable
Shebang : #!/usr/bin/perl
Home : http://www1.cuni.cz/~obo/textutils/ (doc)
Modules : (for perl codes)
Getopt::Long 2.42
arrange Arrange fields, like cut, but in user-specified order. (what)
Path : ~/bin/arrange
Version : 1.15
Length : 355 lines
Type : Perl script, ASCII text executable
Shebang : #!/usr/bin/perl
Modules : (for perl codes)
warnings 1.23
strict 1.08
Carp 1.3301
Getopt::Euclid 0.4.5最美好的祝愿..。干杯,drl
发布于 2019-07-29 03:01:30
sed -e '
s/,/\n/7 ;# tag the end of col7
s/^/,/ ;# add a comma
s/,/\n/2 ;# tag beginning of col2
s/.*\n\(.*\)\n.*/\1/ ;# perform surgery
' file.csv<#>结果:
column2,column3,column4,column5,column6,column7https://unix.stackexchange.com/questions/532599
复制相似问题