在shell脚本中基于行号用参数替换行的特定部分



我有一个脚本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

我该怎么做呢?

谢谢!

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

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

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

最新更新