bash 如何使用 tr 替换 '--' 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1580845/
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-17 21:17:05  来源:igfitidea点击:

How do I use tr to substitute '--' string

linuxbashshell

提问by Guy

I have an output:

我有一个输出:

--
out1
--
out2
--
out3

I want to get the output:

我想得到输出:

out1
out2
out3

I thought of using:

我想过使用:

tr '--' ''

but it doesn't recognize '--' to be the first string I want to substitute. How do I solve this?

但它不承认 '--' 是我想替换的第一个字符串。我该如何解决这个问题?

回答by Amro

cat file | sed '/^--/d'

回答by Jerry Coffin

Why not use grep -v "^--$" yourfile.txt?

为什么不使用grep -v "^--$" yourfile.txt

回答by ghostdog74

another way with awk

awk 的另一种方式

awk '!/^--$/' file

回答by Paused until further notice.

The best you can do with tris delete the hyphens leaving blank lines. The best way to do what you want is Amro's answerusing sed. It's important to remember that trdeals with lists of characters rather than multi-character strings so there's no point in putting two hyphens in your parameters.

您能做的最好的事情tr是删除连字符,留下空行。做你想要什么,最好的办法是荷银的答案使用sed。重要的是要记住,它tr处理的是字符列表而不是多字符串,因此在参数中放置两个连字符是没有意义的。

$ tr -d "-" < textfile
out1

out2

out3

However, in order to have trhandle hyphens and additional characters, you have to terminate the options using --or put the hyphen after the last character. Let's say you want to get rid of hyphens and letter-o:

但是,为了tr处理连字符和附加字符,您必须使用--或将连字符放在最后一个字符之后终止选项。假设您想去掉连字符和字母 o:

$ tr -d "-o" < textfile
tr: invalid option -- 'o'
Try ‘tr --help' for more information.

$ tr -d -- "-o" < textfile
ut1

ut2

ut3

$ tr -d "o-" < textfile
ut1

ut2

ut3

It's often a good idea to use the --option terminator when the character list is in a variable so bad data doesn't create errors unnecessarily. This is true for commands other than tras well.

--当字符列表在变量中时使用选项终止符通常是个好主意,这样坏数据就不会产生不必要的错误。这适用于其他命令tr

tr -d -- "$charlist" < "$file"

回答by VNS

You can do the same thing with grepas well:

你也可以做同样的事情grep

cat filename |grep -v "\--"