使用bash从文本文件中删除符号(Use bash to remove symbols from text file)

编程入门 行业动态 更新时间:2024-10-23 12:33:21
使用bash从文本文件中删除符号(Use bash to remove symbols from text file)

我有一堆包含这样的东西的txt文件:

text_i_need_to_remove{text_i_need_to_retain} text_i need_to_remove{text_i_need_to_retain} ...

如何在花括号(和花括号本身)之前删除文本并仅保留text_i_need_to_retain ?

I have a bunch of txt-files containing stuff like this:

text_i_need_to_remove{text_i_need_to_retain} text_i need_to_remove{text_i_need_to_retain} ...

How do I remove text before curly braces (and curly braces themselves) and retain just only text_i_need_to_retain?

最满意答案

在行尾删除最多{或}所有内容

:%s/.*{\|}$//g

从bash shell,您可以使用sed和awk等文本处理工具。 假设文件名为ip.txt

1)使用sed ,这与我们在vim使用的正则表达式非常相似。 -i标志允许在适当的位置进行更改,即它会修改输入文件本身。

$ sed -i 's/.*{\|}$//g' ip.txt

2)使用awk ,可以再次使用替换,或者在这种情况下,在大括号上拆分行并仅使用第二列。

$ awk -F'{|}' '{print $2}' ip.txt > tmp && mv tmp ip.txt

如果你有GNU awk ,就会有-i inplace选项进行就地编辑

$ gawk -i inplace -F'{|}' '{print $2}' ip.txt

要更改当前目录中的所有文件,请使用

sed -i 's/.*{\|}$//g' *

或者,如果他们有共同的扩展名,比如.txt ,请使用

sed -i 's/.*{\|}$//g' *.txt

Deleting everything upto { or } at end of line

:%s/.*{\|}$//g

From bash shell, you can use text processing tools like sed and awk. Assume file is named ip.txt

1) With sed, which is pretty similar to regex we used inside vim. The -i flag allows to make change in place, i.e it modifies the input file itself.

$ sed -i 's/.*{\|}$//g' ip.txt

2) With awk, one can again use substitution or in this case, split the line on curly brackets and use only the second column.

$ awk -F'{|}' '{print $2}' ip.txt > tmp && mv tmp ip.txt

If you have GNU awk, there is -i inplace option for in place editing

$ gawk -i inplace -F'{|}' '{print $2}' ip.txt

To make changed to all files in current directory, use

sed -i 's/.*{\|}$//g' *

Or if they have common extension, say .txt, use

sed -i 's/.*{\|}$//g' *.txt

更多推荐

本文发布于:2023-08-07 07:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462302.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   符号   bash   remove   file

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!