从bash中的最后一个点中删除所有文本 [英] Remove all text from last dot in 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
+ end of line
并将其替换为空.也就是说,它会删除它.
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屋!