bash 从bash中的最后一个点中删除所有文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26633623/
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
Remove all text from last dot in bash
提问by user3845185
I have a file named test.txt
which has:
我有一个名为的文件test.txt
,其中包含:
abc.cde.ccd.eed.12345.5678.txt
abcd.cdde.ccdd.eaed.12346.5688.txt
aabc.cade.cacd.eaed.13345.5078.txt
abzc.cdae.ccda.eaed.29345.1678.txt
abac.cdae.cacd.eead.18145.2678.txt
aabc.cdve.cncd.ened.19945.2345.txt
If I want to remove everything beyond the first .
like:
如果我想删除第一个之外的所有内容,.
例如:
cde.ccd.eed.12345.5678.txt
cdde.ccdd.eaed.12346.5688.txt
cade.cacd.eaed.13345.5078.txt
cdae.ccda.eaed.29345.1678.txt
cdae.cacd.eead.18145.2678.txt
cdve.cncd.ened.19945.2345.txt
Then I will do
然后我会做
for i in `cat test.txt`; do echo ${i#*.}; done
but If I want to remove everything after the last .
like:
但是如果我想在最后一个之后删除所有内容,.
例如:
abc.cde.ccd.eed.12345.5678
abcd.cdde.ccdd.eaed.12346.5688
aabc.cade.cacd.eaed.13345.5078
abzc.cdae.ccda.eaed.29345.1678
abac.cdae.cacd.eead.18145.2678
aabc.cdve.cncd.ened.19945.2345
what should I do?
我该怎么办?
回答by fedorqui 'SO stop harming'
With awk:
使用 awk:
awk 'BEGIN{FS=OFS="."} NF--' file
In case there are no empty lines, this works. It sets input and output field separators to the dot .
. Then, decreases the number of fields in one, so that the last one is kept out. Then it performs the default awk
action: {print $0}
, that is, print the line.
如果没有空行,这有效。它将输入和输出字段分隔符设置为点.
。然后,减少一个字段的数量,以便将最后一个排除在外。然后它执行默认awk
操作:{print $0}
,即打印该行。
With sed
:
与sed
:
sed 's/\.[^.]*$//' file
This catches the last block of .
+ text
+ end of line
and replaces it with nothing. That is, it removes it.
这会捕获.
+ text
+的最后一个块end of line
并用空替换它。也就是说,它删除了它。
With rev
and cut
:
随着rev
和cut
:
rev file | cut -d'.' -f2- | rev
rev
reverses the line, so that cut
can print from the 2nd word to the end. Then, rev
back to get the correct output.
rev
反转行,以便cut
可以从第二个单词打印到末尾。然后,rev
返回以获得正确的输出。
With bash
:
与bash
:
while ISF= read -r line
do
echo "${line%.*}"
done < file
This perform a string operation consisting in replacing the shortest match of .*
from the end of the variable $line
content.
这将执行字符串操作,包括替换.*
变量$line
内容末尾的最短匹配项。
With grep
:
与grep
:
grep -Po '.*(?=\.)' file
Look-ahead to print just what is before the last dot.
前瞻打印最后一个点之前的内容。
All of them return:
他们都返回:
abc.cde.ccd.eed.12345.5678
abcd.cdde.ccdd.eaed.12346.5688
aabc.cade.cacd.eaed.13345.5078
abzc.cdae.ccda.eaed.29345.1678
abac.cdae.cacd.eead.18145.2678
aabc.cdve.cncd.ened.19945.2345