简体   繁体   中英

Apply shell script to strings inside a file and replace string inside quotes

Suppose I have a file greeting.txt (double quotes are inside the file, only one line):

"Hello world!"

And a file names.txt (no double quotes, many lines, show 2 here as an example):

Tom
Mary

Then I want to create a bash script that create files greeting_to_Tom.txt :

"Hello Tom!"

and greeting_to_Mary.txt :

"Hello Mary!"

I'm quite newbie in shell script, so after I piece together what I searched, I tried:

greetingToAll.sh :

#!/bin/bash
filename="greeting_to_"$1".txt"
cp greeting.txt $filename
sed -i 's/world/$1/' $filename

and at command line I type:

cat names.txt | xargs ./greetingToAll.sh

But only Tom is recognized and it's wrongly replaced by $1 . Anybody can help me with this task?

The problem is in the xargs command. It takes the content of names.txt and puts it as arguments to the ./greetingToAll.sh command. So the resulting call is

./greetingToAll.sh Tom Mary

In this call, $1 is Tom and that's get replaced correctly. You might want to do

cat names.txt | while read name; do ./greetingToAll.sh "$name"; done

This calls ./greetingToAll.sh twice, once as ./greetingToAll.sh "Tom" and once as ./greetingToAll.sh "Mary" .

This awk one-liner can also do the job:

awk 'FNR==NR{a[++n]=$1; next} $2=="world!\"" {
   for (i=1; i<=n; i++){s=$0; sub(/world/, a[i], s);
      print s > "greeting_to_" a[i] ".txt"}}' names.txt greetings.txt

Verify:

grep -H Hello greeting_to_*
greeting_to_Mary.txt:"Hello Mary!"
greeting_to_Tom.txt:"Hello Tom!"

If you create greetingToAll as the below:

greeting=$(cat greeting.txt)
while read -r name; do 
  echo "$greeting" | sed "s/world/$name/" > "greeting_to_$name.txt"
done < "$1"

You can call as:

./greetingToAll names.txt

Depending on what you're doing, it might be an even better idea to parameterise the script to take the greeting from any file you choose:

greeting=$(cat "$1")
while read -r name; do 
  echo "$greeting" | sed "s/world/$name/" > "greeting_to_$name.txt"
done < "$2"

Then can call as:

./greetingToAll greeting.txt names.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