如何拆分在bash字符串由制表符分隔 [英] How to split a string in bash delimited by tab

查看:146
本文介绍了如何拆分在bash字符串由制表符分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在bash拆分标签delimitted场。

I'm trying to split a tab delimitted field in bash.

我知道这个答案:<一href=\"http://stackoverflow.com/questions/3162385/how-to-split-a-string-in-shell-and-get-the-last-field\">how拆壳串并获得最后一个字段

但是,这并不回答制表符。

But that does not answer for a tab character.

我想做获得制表符前的字符串的一部分,所以我这样做:

I want to do get the part of a string before the tab character, so I'm doing this:

x=`head -1 my-file.txt`
echo ${x%\t*}

但\\ t被上的字母T,而不是一个选项卡上的匹配。什么是做到这一点的最好方法是什么?

But the \t is matching on the letter 't' and not on a tab. What is the best way to do this?

感谢

推荐答案

如果你的文件看起来像这样(有标签作为分隔符):

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

如果你使用 AWK ,也没有必要使用来获得最后一行,改变的输入:

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

解决方案用awk:

Solution using awk:

$ awk 'END {print $1}' input
10:1st-field

纯bash的解决方案:

Pure bash-solution:

#!/bin/bash

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

输出:

$ ./tab.sh 
10:1st-field

最后,利用溶液 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%   *}

输出:

1st-field

这篇关于如何拆分在bash字符串由制表符分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆