简体   繁体   English

Bash 替换 tail -f 后的前 4 个字符

[英]Bash replace first 4 characters after tail -f

I have a log-file as.txt where I want the first four characters to be replaced by **** or XXXX to anonymize the data.我有一个日志文件 as.txt,我希望将前四个字符替换为****XXXX以匿名数据。

I am running the following command:我正在运行以下命令:

tail -f file.txt

I know I can cut the first characters the following way:我知道我可以通过以下方式剪切第一个字符:

tail -f file.txt | cut -c4-

But I would then like to insert four wildcard characters.但是我想插入四个通配符。

How can I achieve this?我怎样才能做到这一点?

echo 1234567890 | sed 's/..../****/'

Output: Output:

****567890

To tail the file continuously with the first four characters anonymized, you can use the following command:要以匿名的前四个字符连续尾随文件,可以使用以下命令:

tail -f file.txt | sed 's/^..../****/'

If you have a file that's done being written to and you want to anonymize all the data in it at once, you can use sed as follows:如果您有一个已完成写入的文件,并且您想一次匿名化其中的所有数据,您可以使用 sed,如下所示:

sed -i 's/^..../****/g' 58486880.txt

Note that this second command works with GNU/Linux sed, but not BSD/MacOS sed.请注意,第二个命令适用于 GNU/Linux sed,但不适用于 BSD/MacOS sed。

Because the question and title do not match, to replace the last four you have to use $ as such:因为问题和标题不匹配,要替换最后四个,您必须使用$

tail -f tmp.txt | sed 's/.\{4\}$/****/'

To test:去测试:

 while true; do cat <(seq 1 10 | tr -d '\n') <(echo) >> tmp.txt; sleep 1; done

This produces:这会产生:

1234567****
1234567****
1234567****
1234567****
1234567****
1234567****
1234567****
1234567****
1234567****
1234567****
1234567****
1234567****
1234567****
1234567****
1234567****

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

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