繁体   English   中英

如何使用多个字段分隔符打印字段

[英]How to print fields using multiple field separators

我正在寻找使用空格和点来分隔数据的第二列和最后一列的值。

我的输入是

abcds 874598 thd/vb.sbds/jf 48459 com.dat.first.NAME

所需的输出是

874598 NAME 

使用awk

$ awk -F'[. ]' '{print $2, $NF}' file
874598 NAME

-F选项将字段分开设置,我们提供包含空格或句点的字符类 Awk使用字段分隔符值将文件中的每一行溢出到字段中,并将它们存储在递增引用中, $1是第一个字段, $2是第二个字段。 NF是对当前记录中字段数的引用, $NF是最后一个字段的值。

您可以将命令读取为:

awk               # the command; awk takes a script and executes it on every input line
-F'[. ]'          # the field separator; break each line up using spaces or periods
'{print $2, $NF}' # the script to execute; print the second and last field on every line
 file             # the input file to run the script on

使用read和纯BASH:

s='abcds 874598 thd/vb.sbds/jf 48459 com.dat.first.NAME'
IFS=$' \t.' read -ra arr <<< "$s"
echo "${arr[1]} ${arr[-1]}"
874598 NAME

分解:

IFS=' .'    # sets input field separator as space or dot
read -ra    # reads all fields into an array
${arr[1]}   # represents 2nd element in array
${arr[-1]}  # represents last element in array

从您的评论听起来像您想要的:

$ awk -F '[[:space:]]+|[.]' '{print $2, $NF}' file
874598 NAME

要么:

$ awk '{sub(/.*\./,"",$NF); print $2, $NF}' file  
874598 NAME

暂无
暂无

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

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