Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

bash - Print multiple fields in AWK but split one of them based on a different delimiter

Is there an easy way to split a field, get the first element from the said split field AND also print other fields in same awk?

I want to modify below such that is works for $2 not just when it's MCU:123 but also when it's DISNEY:654 such that $2 returns MCU or DISNEY depending on the string. Obviously substr was a bad choice there.

 awk 'BEGIN{FS=OFS=""}{print $1,substr($2,1,3)}'

Sample of two fields tab seperated

1  mcu:1234   
2  disney:234 

Expected result tab seperated

1  mcu    
2  disney
question from:https://stackoverflow.com/questions/65940555/print-multiple-fields-in-awk-but-split-one-of-them-based-on-a-different-delimite

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$ cut -d: -f1 file
1       mcu
2       disney

or if the real file is more convoluted than the example in your question then maybe this will do what you really need:

$ awk -F'[:]' -v OFS='' '{print $1, $2}' file
1       mcu
2       disney

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...