[英]sed: replace from the last occurrence of “-” till EOL
I have a file with items, one per line. 我有一个包含项目的文件,每行一个。 The item contains at least one dash, and I would like to remove the last dash and the words that follow.
该项目至少包含一个短划线,我想删除最后一个短划线和后面的单词。 For example:
例如:
item asdkalqndla-asdnkfsv-324we-blueray
item asda-vbght564e-dfg-redapple
item gefdsc-fgy-543-5trr-floatingvanilla
Should give: 应该给:
item asdkalqndla-asdnkfsv-324we
item asda-vbght564e-dfg
item gefdsc-fgy-543-5trr
sed 's/\-.*$//' lines.txt
Which gives 这使
item asdkalqndla
item asda
item gefdsc
Because the regex is greedy, and consumes everything from the first dash onwards. 因为正则表达式是贪婪的,并且从第一次破折号开始消耗所有东西。
How can I remove all characters from the last -
in a string till EOL? 如何删除最后一个字符
-
字符串直到EOL?
With awk
: 用
awk
:
$ awk '{sub(/-[^-]*$/,""); print}' file
item asdkalqndla-asdnkfsv-324we
item asda-vbght564e-dfg
item gefdsc-fgy-543-5trr
Simple negation using ^\\-
solved the problem: 使用
^\\-
简单否定解决了问题:
$ sed 's/\-[^\-]*$//' lines.txt
item asdkalqndla-asdnkfsv-324we
item asda-vbght564e-dfg
item gefdsc-fgy-543-5trr
This way, sed replaces a dash followed by anything-but-dash till the end of the line. 这样,sed替换了一个破折号,后跟任何东西 - 但是破折号直到行尾。
Following simple awk
may help you in same. 以下简单的
awk
可以帮助你。
awk -F"-" 'NF{NF=(NF-1)} 1' OFS="-" Input_file
Output will be as follows. 输出如下。
item asdkalqndla-asdnkfsv-324we
item asda-vbght564e-dfg
item gefdsc-fgy-543-5trr
Explanation: -F"-"
: Making field separator as -
for each line for Input_file. 说明:
-F"-"
:将字段分隔符设置为-
对于Input_file的每一行。
NF{NF=(NF-1)}
: awk
has out of the box NF
variable which has number of fields for any line, since we don't text after last occurrence of -
and field separator is -
, by mentioning NF
, we are checking if a line is NOT EMPTY. NF{NF=(NF-1)}
: awk
具有开箱即用的NF
变量,它具有任意行的字段数,因为我们在最后一次出现后没有文本-
而字段分隔符是-
,通过提及NF
,我们正在检查一条线是否是空的。 decrementing the number of field's value with 1
so that we will NOT get the last field. 将字段值的数量减
1
这样我们就不会得到最后一个字段。
1
: awk
works on method of condition
then action
so making condition part TRUE here by mentioning 1 here and not mentioning any action here so by default print of current line will happen. 1
: awk
在condition
然后action
方法上工作所以这里通过提到1并且这里没有提及任何动作使条件部分为TRUE因此默认打印当前行将发生。
OFS="-"
: Making OFS
output field separator as "-"
here so that -
will come in output. OFS="-"
:在这里使OFS
输出字段分隔符为"-"
,以便-
将输出。
EDIT: Shorter versions of decrementing NF
too as follows. 编辑:递减
NF
较短版本如下。
awk -F"-" 'NF{NF-=1} 1' OFS="-" Input_file
OR 要么
awk -F"-" 'NF{NF--} 1' OFS="-" Input_file
This might work for you (GNU sed): 这可能适合你(GNU sed):
sed 's/\(.*\)-.*/\1/' file
Used greed to find the last -
and replace the whole line with what came before it. 使用贪婪找到最后一个
-
并用之前的内容替换整行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.