删除bash中最后一个点的所有文本 [英] Remove all text from last dot in bash

查看:73
本文介绍了删除bash中最后一个点的所有文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 test.txt 的文件,该文件具有:

I have a file named test.txt which has:

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

那我会做

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

我该怎么办?

推荐答案

使用awk:

awk 'BEGIN{FS=OFS="."} NF--' file

如果没有空行,则可以使用.它将输入和输出字段分隔符设置为点..然后,减少一个字段的数量,以便保留最后一个字段.然后,它执行默认的 awk 操作: {print $ 0} ,即打印该行.

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.

使用 sed :

sed 's/\.[^.]*$//' file

这将捕获的最后一块. + text + 行尾,然后将其替换为空.也就是说,它将删除它.

This catches the last block of . + text + end of line and replaces it with nothing. That is, it removes it.

带有 rev cut :

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

rev 反转行,以便 cut 可以从第二个单词开始打印到末尾.然后, 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.

使用 bash :

while ISF= read -r line
do
  echo "${line%.*}"
done < file

这将执行字符串操作,其中包括从变量 $ line 内容的末尾替换.* 的最短匹配项.

This perform a string operation consisting in replacing the shortest match of .* from the end of the variable $line content.

使用 grep :

grep -Po '.*(?=\.)' file

先行查看以打印最后一个点之前的内容.

Look-ahead to print just what is before the last dot.

所有人都返回:

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

这篇关于删除bash中最后一个点的所有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆