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

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

Remove all text from last dot in bash

linuxbashawkgrep

提问by user3845185

I have a file named test.txtwhich 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 awkaction: {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 lineand replaces it with nothing. That is, it removes it.

这会捕获.+ text+的最后一个块end of line并用空替换它。也就是说,它删除了它。

With revand cut:

随着revcut

rev file | cut -d'.' -f2- | rev

revreverses the line, so that cutcan print from the 2nd word to the end. Then, revback 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 $linecontent.

这将执行字符串操作,包括替换.*变量$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