linux - 用适当数量的 "*"替换偶数词

标签 linux bash

我需要输入一些行数,用适当数量的“*”替换偶数行上的所有单词并将结果输出到屏幕。

例如输入:

Hi! How are you? 

It's been a while since we've met.

会给我们:

Hi! *** are ****

It's **** a ***** since ***** met.

这是我尝试过的:

#!/bin/bash

res=""

mm="*"

i=0

while IFS= read -r line; do 

for word in line

do

tmp=""

lng=${#word}

if [ $(($lng % 2)) -eq 0 ]; 

then

while [ $i -lt $lng ]; do

tmp=$tmp$mm

let i=i+1

done

res+=${tmp}

else

res+=${word}

fi

done

done

echo -e "${res}"

但是它并没有做它应该做的事情(

有什么建议吗?

最佳答案

作为 perl 的一行代码:

$ echo "Hi! How are you?\nIt's been a while since we've met." \
   | perl -pe 's/\S+\s+\K(\S+)/"*" x length($1)/eg'
Hi! *** are ****
It's **** a ***** since ***** met.

基本上,对于每对由空格分隔的单词,用与其长度相等的星号替换第二个单词。

关于linux - 用适当数量的 "*"替换偶数词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58679426/

相关文章:

linux - 使用 Linux 命令查找并替换

linux - 为什么管道上的这个 strace 没有完成

mysql - shell脚本中的条件mysql操作

bash - 如何使用 bash 替换 csv 文件中特定位置的字符串

java - 在 unix 机器上渲染美国单位分隔符

linux - pthread 读写器锁和基于 fcntl() 的文件锁有什么区别?

linux - 通过网络获取最新版本 rpm 的最有效方法

c - 在非实时操作系统/内核上执行接近实时任务的最佳方法是什么?

json - 如何使用 Bash 删除 json 文件中的最后一个逗号?

linux - 如何 tgz 目录中的所有项目并使用 GnuPG 即时加密?