剪切并替换 bash
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13588949/
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
Cut and replace bash
提问by ulkar
I have to process a file with data organized like this
我必须处理一个包含这样组织的数据的文件
AAAAA:BB:CCC:EEEE:DDDD
FF:III:JJJ:KK:LLL
MMMM:NN:OOO:PP
etc
Columns can have different length but lines always have the same number of columns.
列的长度可以不同,但行的列数始终相同。
I want to be able to cut a specific column of a given line and change it to the value I want.
我希望能够剪切给定行的特定列并将其更改为我想要的值。
For example I'd apply my command and change the file to
例如,我会应用我的命令并将文件更改为
AAAAA:BB:XXXX:EEEE:DDDD
FF:III:JJJ:KK:LLL
MMMM:NN:OOO:PP
I know how to select a specific line with sed and then cut the field but I have no idea on how to replace the field with the value I have.
我知道如何使用 sed 选择特定行,然后剪切该字段,但我不知道如何用我拥有的值替换该字段。
Thanks
谢谢
回答by sampson-chen
Here's a way to do it with awk:
这是一种方法awk:
Going with your example, if you wanted to replace the 3rd field of the 1st line:
以您的示例为例,如果您想替换第一行的第三个字段:
awk 'BEGIN{FS=OFS=":"} {if (NR==1) { = "XXXX"}; print}' input_file
Input:
输入:
AAAAA:BB:CCC:EEEE:DDDD
FF:III:JJJ:KK:LLL
MMMM:NN:OOO:PP
Output:
输出:
AAAAA:BB:XXXX:EEEE:DDDD
FF:III:JJJ:KK:LLL
MMMM:NN:OOO:PP
Explanation:
解释:
- awk: invoke the awk command
- '...': everything enclosed by single-quotes are instructions to awk
- BEGIN{FS=OFS=":"}: Use- :as delimiters for both input and output.- FSstands for Field Separator.- OFSstands for Output Field Separator.
- if (NR==1) {$3 = "XXXX"};: If Number of Records (- NR) read so far is 1, then set the 3rd field (- $3) to "- XXXX".
- print: print the current line
- input_file: name of your input file.
- awk: 调用 awk 命令
- '...': 用单引号括起来的所有内容都是 awk 的指令
- BEGIN{FS=OFS=":"}:- :用作输入和输出的分隔符。- FS代表字段分隔符。- OFS代表输出字段分隔符。
- if (NR==1) {$3 = "XXXX"};:如果- NR到目前为止读取的记录数 ( ) 为 1,则将第 3 个字段 (- $3) 设置为“- XXXX”。
- print: 打印当前行
- input_file: 输入文件的名称。
If instead what you are trying to accomplish is simply replace all occurrences of CCCwith XXXXin your file, simply do:
相反,如果您想要完成的只是替换文件中所有出现的CCCwith XXXX,只需执行以下操作:
sed -i 's/CCC/XXXX/g` input_file
Note that this will also replace partial matches, such as ABCCCDD-> ABXXXXDD
请注意,这也会替换部分匹配,例如ABCCCDD->ABXXXXDD
回答by potong
This might work for you (GNU sed):
这可能对你有用(GNU sed):
sed -r 's/^(([^:]*:?){2})CCC/XXXX/' file
or
或者
awk -F: -vOFS=: '=="CCC"{="XXXX"};1' file

