views:

594

answers:

2

Let me start off by saying that I know there is probably a much simpler way to do this. But this is what i have and yes hopefully I can make some improvements and/or simplifications at the end.

Goal as of this moment

To double space the output stored in the $tmp variable below and individually number each line. Doing this should give me each set of executable commands on separate lines.

Problem 1

I've tried everything that I can think of to double space what's in the variable. Moving the double space command around, and changing the command itself.

To number the files I've tried to modify this code:

 sed = filename | sed 'N; s/^/ /; s/ *\(.\{6,\}\)\n/\1 /

And of course experimented around with awk but no progress..

Not so Long Term Goals

  • To execute these commands one by one and compare the difference in bytes. Or just any general difference. I know at this point I can use the diff command with file1 file2 and then save the output in some variable like: "$diffA $diffB" and updating it each time using a loop for the chance that more than 2 files are passed as arguments.
  • To tell the difference between each command line. And echo something like:

line 1 in file1 is different from line 1 in file2, check it out: "$diffA $diffB"

Here is what i have so far, its a start:

#!/bin/bash

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 '/regex /!p' | sed -n '/regex /!p' | sed -n '/"regex"/,+1!p' | sed -n '/======/!p' | sed -n '/regex/!p' | sed -n '/regex\
\r/!p' | sed -n '/regex /!p' )

fi

MyVar=$(echo $tmp)

echo "$MyVar | sed G"

FILE2="$2"
if [ -f $FILE2 ]; then
    if [ -f $FILE2 ]; then
         tmp2=$(cat $FILE2 | sed -n '/regex/,/regex/{/regex\ S/d;p}' |\ 
sed -n '/#/!p' | sed -e s/[^:]*:// | sed /--------/,+10d)
     fi


echo "$tmp2"

Any help is very much appreciated.

+1  A: 

The following awk script will double space the output and number the lines:

awk ' { print NF " " $0; print ""; }'

Your problem is to assign this to a variable:

( echo a; echo b) | awk ' { print NR " " $0; print ""; }'

gives:

1 a

2 b

but

tmp=$(( echo a; echo b) | awk ' { print NR " " $0; print ""; }')
echo "$tmp"

gives

1 a 2 b

because using $() will replace the linefeeds with blanks. You will have to use a temporary file:

tmp=$(mktemp)
awk ' { print NR " " $0; print ""; }' $FILE > $tmp
cat $tmp # Do something with the file
rm $tmp # Don't forget to clean up after yourself.
Aaron Digulla
A: 

An alternative to using a temporary file is to use quotes to suppress the newline/space substitution:

tmp="$(echo a; echo b)"
echo "$tmp"
meingbg