java split tab分割_如何在由tab分隔的bash中拆分字符串 (How to split a string in bash delimited by tab)...

本文介绍了如何使用awk、cut和sed工具从含有tab分隔的数据中提取第一字段,展示了三种方法的操作步骤,并强调了它们在实际场景中的应用。最后给出了纯bash解决方案和使用正则表达式操作最后一行的例子。
摘要由CSDN通过智能技术生成

If your file look something like this (with tab as separator):

1st-field 2nd-field

you can use cut to extract the first field (operates on tab by default):

$ cut -f1 input

1st-field

If you're using awk, there is no need to use tail to get the last line, changing the input to:

1:1st-field 2nd-field

2:1st-field 2nd-field

3:1st-field 2nd-field

4:1st-field 2nd-field

5:1st-field 2nd-field

6:1st-field 2nd-field

7:1st-field 2nd-field

8:1st-field 2nd-field

9:1st-field 2nd-field

10:1st-field 2nd-field

Solution using awk:

$ awk 'END {print $1}' input

10:1st-field

Pure bash-solution:

#!/bin/bash

while read a b;do last=$a; done < input

echo $last

outputs:

$ ./tab.sh

10:1st-field

Lastly, a solution using sed

$ sed '$s/\(^[^\t]*\).*$/\1/' input

10:1st-field

here, $ is the range operator; i.e. operate on the last line only.

For your original question, use a literal tab, i.e.

x="1st-field 2nd-field"

echo ${x% *}

outputs:

1st-field

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值