Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

linux - For each line in file execute command synchronously and save to newline of another file

I have a wget script named Chktitle.sh -- this script takes a command like below

$ Chktitle.sh "my url"

I then have a file name url.txt with over 100 lines with urls and ips to check for web-page titles. Then i have results.txt as a blank file.

Is there any way I can perform a repetitive action like below for each line in the file:

 Grab line1 from url.txt
 -----
 then execute Chktitle.sh "line1"
 -----
 Now save the result for line1 in results.txt
 -----
 Now goto Line2 ........


 etc etc etc

I need to make sure that it will only execute the next line after the previous one has finished. Can any one show me any easy way to perform this? I am happy to use Perl, sh, and consider other languages..

The contents of chktitle.sh:

#!/bin/bash
string=$1"/search/"
wget --quiet -O - $string 
| sed -n -e 's!.*<title>(.*)</title>.*!1!p'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Maybe something like this could help (provided that I understood correctly) :

while read line; do
    /path/to/Chktitle.sh x"$line" >> results.txt;
done < /path/to/input.txt

For each line in /path/to/input.txt, execute your script and append the output (>>) to results.txt.

Of course you could always add additional statements in your while loop :

while read line; do
    # Initialise var to output of chktitle
    var=$(/path/to/Chktitle.sh x"$line");

    # Add conditions
    if [ "$var" = "google" ]; then
        echo "google" >> result.txt;
    else
        echo "not google" >> result.txt;
    fi
done < /path/to/input.txt

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...