简体   繁体   English

如何在Linux终端命令中从输出中删除字符串的所有实例

[英]How to remove all instances of a string from output in linux terminal commands

This command almost does everything I am needing 这个命令几乎可以完成我需要的一切

cat /etc/passwd | cut -f6- -d : | sort | uniq 

but I can't figure out how to sort out a specific string 但我不知道如何整理一个特定的字符串

I need to remove "/remove/this" from any line where it occurs and I need the lines of text not to be broken up for 1 word per line. 我需要从出现的任何行中删除“ / remove / this”,并且我需要不要将文本行分解成每行1个单词。

The purpose of the command is List all of the shells used by at least one user on the system, without duplicates. 该命令的目的是列出系统上至少一个用户使用的所有外壳程序,而不重复。

Wold appreciate any input. 非常感谢任何投入。

You can use sed . 您可以使用sed When the pattern you are looking for contains / , you should use a different separator character. 当要查找的模式包含/ ,应使用其他分隔符。 I find : quite readable. 我发现:可读性强。

cat /etc/passwd | cut -f6- -d : | sort | uniq | sed s:/remove/this::

Since sed will change some lines, it's better to move sort + uniq to the end of the pipeline. 由于sed将更改某些行,因此最好将sort + uniq移动到管道的末尾。 sort -u combines both programs. sort -u组合了两个程序。

cat /etc/passwd | cut -f6- -d : | sed s:/remove/this:: | sort -u

You can use a single awk command for that: 您可以为此使用单个awk命令:

awk -F: '{sub(/\/remove\/this/, "", $NF);a[$NF]} END{for(i in a){print i}}' /etc/passwd

-F: splits the line by : . -F:通过分割线:

The first block runs on every line of input while sub(/\\/remove\\/this/, "", $NF) removes the string from the last column and a[$NF] creates and index for every shell found in passwd. 第一个块在输入的每一行上运行,而sub(/\\/remove\\/this/, "", $NF)从最后一列删除字符串,并且a[$NF]为在passwd中找到的每个shell创建和索引。 Obviously if the index already exists, it will not get created again. 显然,如果索引已经存在,将不会再次创建它。 Doing so we dedup the data. 这样做我们对数据进行了精简。

At the END of input we are iterating trough the array a and print every index: {for(i in a){print i}} 在输入END ,我们遍历数组a并打印每个索引: {for(i in a){print i}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM