Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How to split a string in bash delimited by tab

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

I am aware of this answer: how to split a string in shell and get the last field

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%*}

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

Thanks

question from:https://stackoverflow.com/questions/6654849/how-to-split-a-string-in-bash-delimited-by-tab

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

1 Answer

0 votes
by (71.8m points)

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/(^[^]*).*$/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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...