bash 从文本文件中提取一行中的第二个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25491847/
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
Extract The Second Word In A Line From A Text File
提问by Aaron Perry
I am currently in need to extract the second word (CRISTOBAL) in a line in a text file.
我目前需要在文本文件的一行中提取第二个单词 (CRISTOBAL)。
* CRISTOBAL AL042014 08/05/14 12 UTC *
The second word in the line "CRISTOBAL" will vary from day to day so, I just need to find a way to extract JUST the second word/character from the line.
“CRISTOBAL”行中的第二个单词每天都会有所不同,因此,我只需要找到一种方法来仅从该行中提取第二个单词/字符。
回答by zedfoxus
2nd word
第二个字
echo '* CRISTOBAL AL042014 08/05/14 12 UTC *' | awk '{print }'
will give you CRISTOBAL
会给你 CRISTOBAL
echo 'testing only' | awk '{print }'
will give you only
会给你 only
You may have to modify this if the structure of the line changes.
如果线路的结构发生变化,您可能需要对此进行修改。
2nd word from lines in a text file
文本文件中的行中的第二个单词
If your text file contains the following two sentences
如果你的文本文件包含以下两句话
this is a test
* CRISTOBAL AL042014 08/05/14 12 UTC *
running awk '{print $2}' filename.txt
will return
跑步awk '{print $2}' filename.txt
会回来
is
CRISTOBAL
2nd character
第二个字符
echo 'testing only' | cut -c 2
This will give you e
, which is the 2nd character, and you may have to modify this so suit your needs also.
这会给你e
,这是第二个字符,你可能需要修改它以适应你的需要。
回答by NeronLeVelu
In case of sed is needed /only available
在需要 sed 的情况下/仅可用
sed '^ *[^ ]* *\([^ ]*\) .*//' YourFile
Take second non blank group (assuming there is at least 1 blank after the word
取第二个非空白组(假设单词后面至少有 1 个空白
But I prefer cut for speed (and awk if any manip is needed).
但我更喜欢剪切速度(如果需要任何操作,则使用 awk)。
In fact it mainly depend on next action in script (if any).
事实上,它主要取决于脚本中的下一个动作(如果有的话)。