I am having trouble with the code below:
IFS=: read c1 c2 c3 c4 rest <<< "$line"
Don't get me wrong this code works good but it doesn't seem to be used for ksh. I basically need to write the same code without the "<<<". There is not much info on the "<<<" online. If anybody has any ideas it would be much appreciated.
EDIT:
Ok code is as follows for the entire portion of programming:
m|M)
#Create Modify Message
clear
echo " Modify Record "
echo -en '\n'
echo -en '\n'
while true
do
echo "What is the last name of the person you would like to modify:"
read last_name
if line=$(grep -i "^${last_name}:" "$2")
then
oldIFS=$IFS
IFS=:
set -- $line
IFS=$oldIFS
c1=$1
c2=$2
c3=$3
c4=$4
shift; shift; shift; shift
rest="$*"
echo -e "Last Name: $1\nFirst Name: $2\nState: $4"
while true
do
echo "What would you like to change the state to?:"
read state
if echo $state | egrep -q '^[A-Z]{2}$'
then
echo "State: $state"
echo "This is a valid input"
break
else
echo "Not a valid input:"
fi
done
echo -e "Last Name: $c1\nFirst Name: $c2\nState: $state"
echo "State value changed"
break
else
echo "ERROR: $last_name is not in database"
echo "Would you like to search again (y/n):"
read modify_choice
case $modify_choice in [Nn]) break;; esac
fi
done
;;
Ok so everything works except for the
echo -e "Last Name: $c1\nFirst Name: $c2\nState: $state"
It will just show:
Last Name:
First Name:
State:
So I can see it is not adding it to my echo correctly.
FINAL EDIT
CODE:
#Case statement for modifying an entry
m|M)
#Create Modify Message
clear
echo " Modify Record "
echo -en '\n'
echo -en '\n'
while true
do
echo "What is the last name of the person you would like to modify:"
read last_name
if line=$(grep -i "^${last_name}:" "$2")
then
echo "$line" |
while IFS=: read c1 c2 c3 c4 rest; do
echo -e "Last Name: $c1\nFirst Name: $c2\nState: $c4"
last=$c1
first=$c2
done
while true
do
echo "What would you like to change the state to?:"
read state
if echo $state | egrep -q '^[A-Z]{2}$'
then
echo "State: $state"
echo "This is a valid input"
break
else
echo "Not a valid input:"
fi
done
echo -e "Last Name: $last\nFirst Name: $first\nState: $state"
echo "State value changed"
break
else
echo "ERROR: $last_name is not in database"
echo "Would you like to search again (y/n):"
read modify_choice
case $modify_choice in [Nn]) break;; esac
fi
done
;;
A here string in Bash
command <<<"string"
is basically equivalent to
echo "string" | command
with the obvious exception that the latter uses a pipeline, which means you cannot meaningfully use it with read in particular. A common workaround is to use the set builtin to capture tokens from a string or an external command:
oldIFS=$IFS
IFS=:
set -- $line # no quotes
IFS=$oldIFS
c1=$1
c2=$2
c3=$3
c4=$4
shift; shift; shift; shift
rest="$*" # loses spacing / quoting
Another workaround is to use a loop which iterates just once; this may seem elegant at first, but can lead to rather clunky code if the body of the pseudo-loop is long or complex.
echo "$line" |
while IFS=: read c1 c2 c3 c4 rest; do
: stuff which uses those variables
done
This works around the problem that echo stuff | read variable will run read in a child process and thus immediately forget the value of variable -- the body of the while loop is all the same process in which the read happened, and so the values of the variables it initialized are visible inside the loop.
Another, similar workaround is to delegate the reading and procesIng to a function;
process () {
IFS=: read c1 c2 c3 c4 rest
: stuff which uses those variables
}
echo "$line" | process
Whether this is clunky or elegant depends a lot on what happens in the function. If it's neatly encapsulated, it can be rather attractive; but if you end up passing in a bunch of unrelated variables (or worse, modifying globals inside the function!) it can be quite the opposite.
Related
Have two files:
file1 is having the key words - INFO ERROR
file2 is having the list of log files path - path1 path2
I need to exit out of the script if any of the condition in any of the loops failed.
Here is the Code:
#!/bin/bash
RC=0
while read line
do
echo "grepping from the file $line
if [ -f $line ]; then
while read key
do
echo "searching $key from the file $line
if [ condition ]; then
RC=0;
else
RC=1;
break;
fi
done < /apps/file1
else
RC=1;
break;
fi
done < apps/file2
exit $RC
Thank you!
The ansewer to your question is using break 2:
while true; do
sleep 1
echo "outer loop"
while true; do
echo "inner loop"
break 2
done
done
I never use this, it is terrible when you want to understand or modify the code.
Already better is using a boolean
found_master=
while [ -n "${found_master}" ]; do
sleep 1
echo "outer loop"
while true; do
echo "inner loop"
found_master=true
break
done
done
When you do not need the variable found_master it is an ugly additional variable.
You can use a function
inner_loop() {
local i=0;
while ((i++ < 5)); do
((random=$RANDOM%5))
echo "Inner $i: ${random}"
if [ ${random} -eq 0 ]; then
echo "Returning 0"
return 0
fi
done;
return 1;
}
j=0
while ((j++ < 5 )); do
echo "Out loop $j"
inner_loop
if [ $? -eq 0 ]; then
echo "inner look broken"
break
fi
done
But your original problem can be handles without two while loops.
You can use grep -E "INFO|ERROR" file2 or combining the keywords. When the keywords are on different lines in file1, you can use grep -f file1 file2.
Replace condition with $(grep -c ${key} ${line}) -gt 0 like this:
echo "searching $key from the file $line
if [ $(grep -c ${key} ${line}) -eq 0 ]; then
It will count the each key-word in your log-file. If count=0 (pattern didn't found), running then. If found at least 1 key, running else, RC=1 and exit from loop.
And be sure, that your key-words can't be substrings of the longest words, or you will get an error.
Example:
[sahaquiel#sahaquiel-PC Stackoverflow]$ cat file
correctstringERROR and more useless text
ERROR thats really error string
[sahaquiel#sahaquiel-PC Stackoverflow]$ grep -c ERROR file
2
If you wish to avoid count 2 (because counting first string, obliviously, bad way), you should also add two keys for grep:
[sahaquiel#sahaquiel-PC Stackoverflow]$ grep -cow ERROR file
1
Now you have counted only the words equal to your key, not substrings in any useful strings.
Following code read the test.txt contents and based on first field it redirect third field to result.txt
src_fld=s1
type=11
Logic_File=`cat /home/script/test.txt`
printf '%s\n' "$Logic_File" |
{
while IFS=',' read -r line
do
fld1=`echo $line | cut -d ',' -f 1`
if [[ $type -eq $fld1 ]];then
query=`echo $line | cut -d ',' -f 3-`
echo $query >> /home/stg/result.txt
fi
done
}
Following is the contents of test.txt:
6,STRING TO DECIMAL WITHOUT DEFAULT,cast($src_fld as DECIMAL(15,2) $tgt_fld
7,STRING TO INTERGER WITHOUT DEFAULT,cast($src_fld as integer) $tgt_fld
11,DEFAULT NO RULE,$src_fld
everything works fine except output in result.txt is $src_fld instead of s1. Can anyone please tell me what is wrong in the code?
Try replacing the below line
echo $query >> /home/stg/result.txt
with this one
eval "echo $query" >> /home/stg/result.txt
I have a UNIX script written in korn shell. I need to make it so that this statement:
while true
do
echo "What is the last name of the person you would like to modify:"
read last_name
if line=$(grep -i "^${last_name}:" "$2")
then
IFS=: read c1 c2 c3 c4 rest <<< "$line"
echo -e "Last Name: $c1\nFirst Name: $c2\nState: $c4"
while true
do
echo "What would you like to change the state to?:"
read state
if [[ $state -eq [A-Z] ]];then
echo "State: $state"
echo "This is a valid input"
break
else
echo "Not a valid input:"
fi
done
else
echo "ERROR: $last_name is not in database"
echo "Would you like to search again (y/n):"
read delete_choice
case $delete_choice in [Nn]) break;; esac
fi
done
;;
Specifically, I am having trouble with this code:
if [[ $state -eq [A-Z] ]];then
The point of this program is to modify a record in a text file but will only take the input of state abbreviations such as (MI, WA, KS, ....).
Try something like:
if echo $state | egrep -q '^[A-Z]{2}$'
then
...
fi
^[A-Z]{2}$ means your state starts and ends with CAPS alphabets of length two.
I am using UNIX Korn shell. I am trying to create a program in Unix that will search a text file which is shown below:
Last Name:First Name:City:State:Class:Semester Enrolled:Year First Enrolled
Gilman:Randy:Manhattan:KS:Junior:Spring:2010
Denton:Jacob:Rochester:NY:Senoir:Fall:2009
Goodman:Joshua:Warren:MI:Freshman:Summer:2014
Davidson:Blair:Snohomish:WA:Sophmore:Fall:2013
Anderson:Neo:Seattle:WA:Senoir:Spring:2008
Beckman:John:Ft. Polk:LA:Freshman:Spring:2014
Then take that line and cut it out and display it vertically. So if I search Gilman. It would produce:
Gilman
Randy
Manhattan
KS
Junior
Spring
2010
However included in this I should also be able to produce the following layout:
Last Name: Gilman
First Name: Randy
City: Manhattan
State: KS
Class: Junior
Semester Enrolled: Spring
Year First Enrolled: 2010
Now I have figured out most of it which I will display in my code below:
cat<<MENULIST
A - Add Student Information
D - Delete Student Information
M - Modify Student Information
I - Inquiry on a Student
X - Exit
MENULIST
echo -en '\n'
echo -en '\n'
echo " Pleasa choose one of the following: "
#take input from operation
read choice
case $choice in
a|A) ;;
d|D) ;;
m|M) ;;
i|I)
#Create Inguiry Message
clear
echo " Record Inquiry "
echo -en '\n'
echo -en '\n'
echo "What is the last name of the person"
#Gather search parameter
read last_name
grep -i "$last_name" $1 | cut -f 1-7 -d ':' ;;
x|X) echo "The program is ending" ; exit 0;;
*) echo -en '\n' ;echo "Not an acceptable entry." ;echo "Please press enter to try again"; read JUNK | tee -a $2 ; continue
esac
I am just really having trouble on redirecting input to the proper output. There is much more to the program but this is the relevant portion for this problem. Any help would be appreciated.
EDIT:
Ok the final answer is shown below:
while IFS=: read c1 c2 c3 c4 c5 c6 c7 rest ; do
case "$c1" in
"$last_name" )
echo -e "Last Name: $c1\nFirst Name: $c2\nCity: $c3\nState: $c4\nClass: $c5\nSemester Enrolled: $c6\nYear First Enrolled: $c7\n\n"
;;
esac
done < $1
This performed the intended outcome correctly thank you everyone for your help. I still have some other questions but I will make a new topic for that so it doesn't get to jumbled together.
Replace your line
grep -i "$last_name" $1 | cut -f 1-7 -d ':' ;;
with
awk -F: -vnameMatch="$last_name" \
'$1==nameMatch{
printf("LastName:%s\nFirstName:%s\nCity:%s\nState:%s\nClass:%s\nSemester Enrolled:%s\nYear First Enrolled:%s\n\n", \
$1, $2, $3, $4, $5, $6, $7)
}' $1
;;
It's pretty much the same idea in ksh.
while IFS=: read c1 c2 c3 c4 c5 c6 c7 rest ; do
case "$c1" in
"$last_name" )
printf "LastName:%s\nFirstName:%s\nCity:%s\nState:%s\nClass:%s\nSemester Enrolled:%s\nYear First Enrolled:%s\n\n",
"$c1" "$c2" "$c3" "$c4" "$c5" "$c6" "$c7"
;;
esac
done < $1
I think I've got all the syntax right, but don't have the energy tonight to test :-/ ... If you can use this, and there are problems, post a comment and I'll clean it up.
IHTH.
EDIT:
#Case statement for conducting an inquiry of the file
i|I)
#Create Inguiry Message
clear
echo " Record Inquiry "
echo -en '\n'
echo -en '\n'
echo "What is the last name of the person:"
#Gather search parameter
read last_name
while IFS=: read c1 c2 c3 c4 c5 c6 c7 rest ; do
case "$c1" in
"$last_name" )
printf "Last Name:%s\nFirst Name:%s\nCity:%s\nState:%s\nClass:%s\nSemester Enrolled:%s\nYear First Enrolled:%s\n\n", "$c1", "$c2", "$c3", "$c4", "$c5", "$c6", "$c7"
;;
esac
done < $2
#Case statement for ending the program
x|X) echo "The program is ending" ; exit 0;;
The error message is:
./asg7s: line 26: syntax error at line 93: `)' unexpected
Line 93 is
x|X) echo "The program is ending" ; exit 0;;
Kind of weird because I didn't mess with that part of the program so I know it has to be something in the portion I changed.
RLG
Adding something extra so I can save RLG edit without other's "approval"
This awk should do:
last_name="Gilman"
awk -F: -v name="$last_name" 'NR==1 {for(i=1;i<=NF;i++) h[i]=$i} $1==name {for(i=1;i<=NF;i++) print h[i]FS,$i}' file
Last Name: Gilman
First Name: Randy
City: Manhattan
State: KS
Class: Junior
Semester Enrolled: Spring
Year First Enrolled: 2010
It stores the first line in array h (header).
Then if it finds the pattern, print out array and data.
Here I post an alternative to a shell script, in perl:
perl -F':' -lne '
BEGIN { $name = pop; }
$. == 1 and do { #header = #F; next; };
next if m/^\s*$/;
if ( $F[0] eq $name ) {
for ( $i = 0; $i < #F; $i++ ) {
printf qq|%s: %s\n|, $header[$i], $F[$i];
}
exit 0;
}
' infile Gilman
It uses -F swith to split fields with colon, -l removes last newline character and -n opens input file and process it line by line.
The script accepts two arguments, but I extract the last one before processing assuming it's the name you want to search.
First line is saved in an array called #header and for next lines it compares first field, and in a match, prints each header followed by each field of current line and aborts the program.
It yields:
Last Name: Gilman
First Name: Randy
City: Manhattan
State: KS
Class: Junior
Semester Enrolled: Spring
Year First Enrolled: 2010
I have had to write a script that can execute 2 command line arguments to execute task. In addition to a while-loop. I am having trouble with the if statement on line 16. The shell produces the following:
./asg6s: line 16: syntax error near unexpected token fi'
'/asg6s: line 16:fi
My code is as follows:
#check if number of arguments are 2
if [ $# -ne 2 ]; then
echo "Does not equal two arguments"
echo "Usage $0 inputfile outputfile"
exit 1
fi
# check if input file exists
if [ ! -e $1 ]; then
echo "$1 not found!"
exit 1
fi
#check if input file is empty
if [ ! -s $FILE ] ; then
echo "$1 is empty"
exit 1
fi
# copy contents of first file to second
cat $1 > $2
while true
do
clear
# display the menu
echo "University of Maryland."
echo "purpose of using the app"
echo -en '\n'
echo "Choose one of the following:"
echo "1 Addition"
echo "2 Subtraction"
echo "3 Multiplication"
echo "4 Division"
echo "5 Modulo"
echo "0 Exit"
echo -en '\n'
#take input for operation
read N
case $N in
1) NAME="add";OP="+";;
2) NAME="subtract";OP="-";;
3) NAME="multiply";OP="*";;
4) NAME="divide";OP="/";;
5) NAME="modulo";OP="%";;
0) echo "The progam is ending" ; exit 0;;
*) echo “Not an Acceptable entry.” ;continue;
esac
#take input numbers
echo "Enter two numbers"
read A
read B
#display value on screen and also append in the output file
echo "The operation is to $NAME. The result of $NAME $A and $B is" `expr $A $OP $B`
echo "The operation is to $NAME. The result of $NAME $A and $B is" `expr $A $OP $B` > $2
done
Any help would be appreciated.
Edit:
In the same code above I have been getting a problem with the loop statement. Well I should say the fact that I cannot get the program to print the answer for me after I input to integers into the program. Specifically, it does nothing and goes back to the point where it ask me input for what operation I want to complete. Any help would be appreciated.
Your script is almost working.
After showing the result of the expr your script continues with the while loop and calls clear. If you want to see the result, you must show the result after the clear or read a dummy key input.
Another problem is the variable $OP, that could be a *. When * is evaluated to a set of files, your expr statement will not work.
The shortest changes is adding a read statement and quoting your $OP:
echo "The operation is to $NAME. The result of $NAME $A and $B is" `expr $A "$OP" $B`
echo "The operation is to $NAME. The result of $NAME $A and $B is" `expr $A "$OP" $B` > $2
read dummy
Of course the script can be changed. Do you really want to overwrite $2 with the results or append to the file?
The 2 echo lines can be put together with tee.
I would move the clear to above the while statement and replace the last part of your script with
read A
read B
clear
#display value on screen and also append in the output file
echo "The operation is to ${NAME}. The result of ${NAME} $A and $B is $(expr $A "${OP}" $B)" | tee -a $2
echo
done