简体   繁体   中英

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

I have a script test.sh
He has some arguments like:

./test.sh Forest Cuba World Hello

I made a while read loop to replace each specific part of a line (extractReplaceArgLine) with argument passed in shell script (Forest Cuba World Hello).

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

Consider the file test.txt:

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

So, the output would be:

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

How can I do that?

Thanks !

Use $1 to get the first argument, and then use shift to shift the arguments down. Doing this in a loop will process each argument in sequence.

There's also no need to use cut and sed , you can use the shell's built-in operations.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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