首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >bash中Mth列中字符串N个字符的条件

bash中Mth列中字符串N个字符的条件
EN

Stack Overflow用户
提问于 2019-12-29 18:46:54
回答 4查看 457关注 0票数 1

我有一个样本

代码语言:javascript
复制
$ cat c.csv
a,1234543,c
b,1231456,d
c,1230654,e

我只需要在第二列的第四个字符而不是0或1的情况下进行grep。

输出必须是

代码语言:javascript
复制
a,1234543,c

我只知道

代码语言:javascript
复制
awk -F, 'BEGIN { OFS = FS } $2 ~/^[2-9]/' c.csv

有可能在第四个角色上加上条件吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-12-29 18:48:42

你能试一下吗。

代码语言:javascript
复制
awk 'BEGIN{FS=","} substr($2,4,1)!=0 && substr($2,4,1)!=1' Input_file

或根据教育署网站的建议:

代码语言:javascript
复制
awk 'BEGIN{FS=","} substr($2,4,1)!~[01]' Input_file

解释:在这里添加了对上述代码的详细说明。

代码语言:javascript
复制
awk '                                        ##Starting awk program from here.
BEGIN{                                       ##Starting BEGIN section from here.
  FS=","                                     ##Setting field separator as comma here.
}                                            ##Closing BLOCK for this program BEGIN section.
substr($2,4,1)!=0 && substr($2,4,1)!=1       ##Checking conditions if 4th character of current line is NOT 0 and 1 then print the current line.
' Input_file                                 ##Mentioning Input_file name here.
票数 2
EN

Stack Overflow用户

发布于 2019-12-29 23:28:55

这可能适用于您(GNU或grep):

代码语言:javascript
复制
grep -vE '^([^,]*,){1}[^,]{3}[01]' file

或者:

代码语言:javascript
复制
sed -E '/^([^,]*,){1}[^,]{3}[01]/d' file  

替换该列中m‘-1列的1和n’-1字符的3

票数 2
EN

Stack Overflow用户

发布于 2019-12-30 15:04:53

Grep是答案。但是下面是另一种使用数组和变量替换的方法

代码语言:javascript
复制
test=( $(cat c.csv) ) # load c.csv data to an array
echo ${test[@]//*,???[0-1]*/} # print all items from an array,
# but remove the ones that correspond to this regex *,???[0-1]*
# so 'b,1231456,d' and 'c,1230654,e' from example will be removed
# and only 'a,1234543,c' will be printed
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59522304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档