在分隔符前切一个单词 - Bash

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33009491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:41:28  来源:igfitidea点击:

Cut one word before delimiter - Bash

bashshellcut

提问by sidman

How do I use cutto get one word before the delimiter? For example, I have the line below in file.txt:

如何使用cut在分隔符之前获取一个单词?例如,我在以下行中file.txt

one two three four five: six seven

一二三四五六七

when I use the cutcommand below:

当我使用以下cut命令时:

cat file.txt | cut -d ':' -f1

...then I get everything before the delimiter; i.e.:

...然后我得到了分隔符之前的所有内容;IE:

one two three four five

一二三四五

...but I only want to get "five"

...但我只想得到“五”

I do not want to use awkor the position, because the file changes all the time and the position of "five" can be anywhere. The only thing fixed is that five will have a ":" delimiter.

我不想使用awk或位置,因为文件一直在变化,“五”的位置可以在任何地方。唯一固定的是五个将有一个“:”分隔符。

Thanks!

谢谢!

回答by anubhava

Since you need to use more that one field delimiter here, awkcomes to rescue:

由于您需要在此处使用多个字段分隔符,因此awk可以使用:

s='one two three four five: six seven'
awk -F '[: ]' '{print }' <<< "$s"
five

EDIT:If your field positions can change then try this awk:

编辑:如果您的现场位置可以更改,请尝试以下操作awk

awk -F: '{sub(/.*[[:blank:]]/, "", ); print }' <<< "$s"
five

Here is a BASH one-liner to get this in a single command:

这是一个 BASH 单行代码,可以在单个命令中获得它:

[[ $s =~ ([^: ]+): ]] && echo "${BASH_REMATCH[1]}"
five

回答by Amadan

Pure bash:

纯猛击:

s='one two three four five: six seven'
w=${s%%:*}                 # cut off everything from the first colon
l=${w##* }                 # cut off everything until last space
echo $l
# => five

(If you have one colon in your file, s=$(grep : file)should set up your initial variable)

(如果你的文件中有一个冒号,s=$(grep : file)应该设置你的初始变量)

回答by Adi

you may want to do something like this: cat file.txt | while read line do for word in $line do if [ echo $word | grep ':$'] then; echo $word fi done done

你可能想做这样的事情: cat file.txt | while read line do for word in $line do if [ echo $word | grep ':$'] then; echo $word fi done done

if it is a consistent structure (with different number of words in line), you can change the first line to:

如果是一致的结构(一行中的单词数不同),则可以将第一行更改为:

cat file.txt | cut -d':' -f1 | while read line do ...

cat file.txt | cut -d':' -f1 | while read line do ...

and that way to avoid processing ':' at the right side of the delimeter

这样就可以避免处理分隔符右侧的“:”

回答by Zloj

Try

尝试

echo "one two three four five: six seven" | awk -F ':' '{print $1}' | awk '{print $NF}'

echo "one two three four five: six seven" | awk -F ':' '{print $1}' | awk '{print $NF}'

This will always print the last word before first :no matter what happens

:无论发生什么,这将始终在第一个之前打印最后一个单词