繁体   English   中英

Sed 根据行号在 shell 脚本中用参数替换行的特定部分

[英]Sed to replace a speccificc part of line by argument in shell script based in line number

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

./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 

因此,output 将是:

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

我怎样才能做到这一点?

谢谢 !

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

也不需要使用cutsed ,你可以使用 shell 的内置操作。

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

暂无
暂无

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

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