views:

438

answers:

2

I have redirected some valuable information into a text file. How can I execute each line of that text file in a loop?

What im thinking is to double space my text file, then to use a loop to execute each line invidually. I'm hoping that when i double space the text file every string of commands will have their own line.

For example, this text file:

cat /etc/passwd | head -101 | tail -3 nl /etc/passwd | head -15 | cut -d':' -f1 cat /etc/passwd | cut -d':' -f1,5 | tee users.txt nl /etc/passwd | tail -1 | cut -f1 ls ~/home | nl | tail -1 | cut -f1 ls -lR / 2>/dev/null | sort -n -r +4 | head -1

should look like this when i double space it:

cat /etc/passwd | head -101 | tail -3
nl /etc/passwd | head -15 | cut -d':' -f1
cat /etc/passwd | cut -d':' -f1,5 | tee users.txt
nl /etc/passwd | tail -1 | cut -f1
ls ~/home | nl | tail -1 | cut -f1 ls -lR / 2>/dev/null | sort -n -r +4 | head -1

And then i would use a loop to execute each line.

here is my script:

FILE="$1"

echo "You Entered $FILE"

if [ -f $FILE ]; then

tmp=$(cat $FILE | sed '/./!d' | sed -n '/regex/,/regex/{/regex/d;p}'| sed -n '/---/,+2!p' | sed -n '/#/!p' | sed 's/^[ ]*//' | sed -e\
s/[^:]*:// | sed -n '/==> /!p' | sed -n '/--> /!p' | sed -n '/"lab3.cmd"/,+1!p'\
 | sed -n '/======/!p' | sed -n '/regex/!p' | sed -n '/commands are fun/\
!p' | sed -n '/regex/!p')

fi

MyVar=$(echo $tmp > hi.txt)
echo "$MyVar"

Is this the right way of going about it?

+1  A: 

Why not just have the line separator delimit the commands? You don't need a blank line to delimit them unless your command must be able to contain line separators - and then what if it needed to contain 2 in a row?

Software Monkey
A: 

I'm afraid I don't understand the problem you are trying to solve. If you write commands into a file called commands.txt, you can execute them simply by

sh commands.txt

That executes each line of the file. If you want to do this in a loop I suppose you might try something like

for i in *; do FILE="$i" sh commands.txt; done

Perhaps you can edit your question to make it a bit more concrete?

Norman Ramsey