bash - 用****屏蔽输出卡号

标签 bash shell sed script

我有一项任务,在给定输入文件的情况下,用星号 (*) 屏蔽每个信用卡号的前 12 位数字,并将屏蔽后的数字打印到输出文件中。
卡号示例:

1111-2222-3333-4444
4444-3333-2222-1111
1234-5678-9101-1171
1234 5678 9101 1121
7347_9834_7598_2834
8973#9858#3475#8734
2356`7843`0527`5340
8734=7583=4895=7007
8763+2430+6257_9406
一切都应该在shell脚本中完成
我的解决办法是:
#!/bin/bash

file='cards.txt'
while read data; do
echo $data | sed -r 's/[[:digit:]]{4}/****/;s/[[:digit:]]{4}/****/;s/[[:digit:]]{4}/****/;s/[^0-9,*]+/ /g'
done < $file > cards-masked.txt
关于如何在此任务中使用 sed 的任何更好的想法?

最佳答案

查看示例数据,您似乎总是有 4 个数字由数字以外的字符分隔。
如果您也有兴趣使用 awk 解决方案,您可以先用空格替换除数字以外的所有字符。
然后用 * 替换前 3 列中的所有字符

awk '{gsub(/[^0-9]+/, " ");for (i=1;i<4;i++) gsub(/[0-9]/,"*",$i)}1' cards.txt > cards-masked.txt
一个更易读的版本,有一个简短的解释
awk '{
  gsub(/[^0-9]+/, " ")                    # Replace all chars other than 0-9 with a space
  for (i=1;i<4;i++) gsub(/[0-9]/,"*",$i)  # Loop the first 3 columns, replace all digits with *
}1' cards.txt > cards-masked.txt          # The 1 evaluates to true, printing the whole line
输出
**** **** **** 4444
**** **** **** 1111
**** **** **** 1171
**** **** **** 1121
**** **** **** 2834
**** **** **** 8734
**** **** **** 5340
**** **** **** 7007
**** **** **** 9406

关于bash - 用****屏蔽输出卡号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69443505/

相关文章:

bash - 意外 token ')'

linux - 每 15 分钟运行一次 crontab 不适用于 linux redhat

linux - 使用占位符更新文件内容

linux - Shell 脚本未按预期工作

bash - 如何提取具有公共(public)字段的行

linux - 使用 mkvmerge 在 bash 中进行 for 循环

linux - 如何用新行显示阅读提示

linux - 创建一个不解释任何内容的 heredoc

sed - 这个花括号表示法叫什么?

linux - 使用一个文件从另一个文件中提取指定的行