【问题标题】:Sed to replace a speccificc part of line by argument in shell script based in line numberSed根据行号在shell脚本中通过参数替换行的特定部分
【发布时间】:2021-01-28 22:01:18
【问题描述】:

我有一个脚本 test.sh
他有一些论点,例如:

./test.sh Forest Cuba World Hello

我做了一个 while read 循环,用在 shell 脚本中传递的参数 (Forest Cuba World Hello) 替换行的每个特定部分 (extractReplaceArgLine)。

while read line
do
    extractReplaceArgLine=$(echo "${line}" | cut -d ' ' -f 1)
    echo "${line}" | sed -e "s/"${extractReplaceArgLine}"/What I put Here ?/"
done < test.txt

考虑文件 test.txt :

Ocean is incredible
Spain is my favorite country
Moon calls me everyday
Goodbye World 

所以,输出将是:

Forest is incredible
Cuba is my favorite country
World calls me everyday
Hello World

我该怎么做?

谢谢!

【问题讨论】:

    标签: linux bash shell sed


    【解决方案1】:

    使用$1 获取第一个参数,然后使用shift 将参数下移。在循环中执行此操作将按顺序处理每个参数。

    也不需要cutsed,可以使用shell自带的操作。

    while read firstword restofline
    do
        echo "$1 $restofline"
        shift
    done < test.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 2013-12-23
      • 1970-01-01
      相关资源
      最近更新 更多