简体   繁体   English

根据管道定界符传递字符串/记录

[英]Pass string/record on pipe delimiter basis

Please advice as I have list of records but I need to find out if my record has 5 pipe delimiter and first name matches then print it. 请提供建议,因为我有记录列表,但是我需要确定我的记录是否具有5个管道定界符并且名字匹配,然后再打印它。

For example: 例如:

abc|def|ghi|lmno|pq|rs
abc|def|ghi|lmno
abc|def|ghi
dpo|def|ghi|lmno|fr|pl|nm

But I want only 1st value to pass if loop. 但是我只希望第一个值通过if循环。

if ($string contains "abc" && 5 pipe delimiter )
print $string;

It looks like awk rides to the rescue once more: 看起来awk再次需要救援:

awk -F '|' 'NF == 6 && $1 == "abc" { print }'

There are 6 fields if there are 5 delimiters. 如果有5个定界符,则有6个字段。 You could omit the { print } since that's the default action. 您可以省略{ print }因为这是默认操作。 If you need to pass the value abc to the script (it can vary), use: 如果您需要将值abc传递给脚本(可能会有所不同),请使用:

awk -F '|' -v string=abc 'NF == 6  && $1 == string { print }'

Don't try using match as a variable name. 不要尝试将match用作变量名。

My answer is predicated on the question, which says: 我的回答基于这个问题,它说:

if my record has 5 pipe delimiter and first name matches then print it 如果我的记录有5个管道定界符且名字匹配,则打印

meaning 'if the record has 6 fields separated by pipe delimiters (so there are 5 pipes) and the first field matches the given name, then print the whole record'. 意思是“如果记录中有6个用管道定界符分隔的字段(因此有5个管道),并且第一个字段与给定名称匹配,则打印整个记录”。 If the question means something slightly different, then the answer has to be modified accordingly. 如果问题的含义略有不同,则必须相应地修改答案。

This is Unix; 这是Unix; there are other ways to do the same task, including: 还有其他方法可以执行相同的任务,包括:

grep '^abc|[^|]*|[^|]*|[^|]*|[^|]*|[^|]*$'
sed -n -e '/^abc\(|[^|]*\)\{5\}$/p'

and you could use Perl or Python or … pick your favourite scripting language. 您可以使用Perl或Python,也可以选择您喜欢的脚本语言。 However, the awk solutions are a lot simpler to read than the grep or sed solutions. 但是, awk解决方案比grepsed解决方案更易于阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM