How to use sed with user input - unix

Script performs two things
1.Enables the user input a file name
2.Enables the user to input a line number to view the content
echo "Enter the file name"
read fname
find / -name "$fname" > /tmp/newone.txt
if test $? -eq 0
then
{
echo "File found"
echo "The no of line in the file $fname is `cat /tmp/newone.txt | wc|awk '{pri
nt $1}'`"
echo "Enter the line no"
read lcnt
sed '"$lcnt" p' "$fname"
}
else
{
echo "File not found"
}
fi
Issue
1.Getting error in the sed part
Error message "sed: -e expression #1, char 3: extra characters after command"
how to rectify it ?
2.Can i redirect the output of 'find' to a variable
For example
$flloc =/tmp/newone.txt
so i will be able to use '$flloc' instead of the absolute path

1) This is how you'd go about using your variable in the sed command:
echo "Line no: "
read lcnt
sed -n "$lcnt p" $fname
What was wrong with your original expression is that bash variables aren't interpreted when you use single quotes. Example:
lcnt=5
# prints $lcnt
echo '$lcnt'
# prints 5
echo "$lcnt"
2) To store your find output to a variable, simply do this:
floc=`find / -name $fname` # Here I'm using backticks, not single quotes.

Related

Unix determine if a file is empty

I am attempting to make a script that will check to see if there is any tyext within a file. I have developed the following script. I have made it check to see if there is exactly 2 arguments, see if the file exists, but I am having trouble checking the file for text within it. The code is as follows:
#!/bin/ksh
#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 [ ! -f $1 ]; then
echo "$1 not found!"
exit 1
fi
#Check if input file is null
#This next block of code is where the issue is
if [ grep -q $1 -eq 0 ]; then
echo "$1 must have text within the file"
exit 1
fi
Any help would be appreciated
test's "-s" option checks if the file is empty -- see manual. So your last chunk would become
#Check if input file is null
#This next block of code is where the issue is
if [ ! -s $1 ]; then
echo "$1 must have text within the file"
exit 1
fi
Try using stat
stat -c %s filename

shell script to find the number of occurence of particular word from text file

My file is ss.txt
Another instance started
Another instance started
Another instance started
Another instance started
No instance started
No instance started
No instance started
No instance started
If i use shell script program as this
#!/bin/sh
t=0
#temp=0
echo "Enter filename"
read f1
if [ -f $f1 ]
then
echo "1.count char,words,lines"
echo "2.particular word to find in file"
echo "3.exit"
echo "Enter ur choice?"
read ch
case $ch in
1) wc -c $f1
echo "characters"
wc -w $f1
echo "words"
wc -l $f1
echo "lines" ;;
2) echo "Enter the word whose occurence has to be found"
read c
t='echo $f1 | wc -c'
echo $t ;;
3) exit ;;
esac
else
echo "File does not exist"
fi
If i run this code i get the following output
i could get the option 2 correct that is word occurence is not correct
i get like
Enter filename
ss.txt
1.count char,words,lines
2.particular word in file
3.exit
Enter ur choice?
1
180 ss.txt
characters
24 ss.txt
words
8 ss.txt
lines
This i get correctly but for choice 2 i get like
Enter filename
ss.txt
1.count char,words,lines
2.particular word in file
3.exit
Enter ur choice?
2
Enter the word whose occurence has to be found
Another
0
See i get zero here but output should be 4
change from:
t='echo $f1 | wc -c'
to
t=`grep -o "$c" "${f1}"|wc -l`
Please try below commands as per your requirement
t=grep -c "text" "${f1}" ( -c, --count count of matching lines for each input file)
or
t=grep -o "text" "${f1}" ( -o,Show only the part of a matching line that matches PATTERN.)
bcsmc2rtese001 [~/Shell_p]$ grep -c "Another" ss.txt
4
bcsmc2rtese001 [~/Shell_p]$ grep -o "Another" ss.txt
Another
Another
Another
Another

How can I set a default value when incorrect/invalid input is entered in Unix?

i want to set the value of inputLineNumber to 20. I tried checking if no value is given by user by [[-z "$inputLineNumber"]] and then setting the value by inputLineNumber=20. The code gives this message ./t.sh: [-z: not found as message on the console. How to resolve this? Here's my full script as well.
#!/bin/sh
cat /dev/null>copy.txt
echo "Please enter the sentence you want to search:"
read "inputVar"
echo "Please enter the name of the file in which you want to search:"
read "inputFileName"
echo "Please enter the number of lines you want to copy:"
read "inputLineNumber"
[[-z "$inputLineNumber"]] || inputLineNumber=20
for N in `grep -n $inputVar $inputFileName | cut -d ":" -f1`
do
LIMIT=`expr $N + $inputLineNumber`
sed -n $N,${LIMIT}p $inputFileName >> copy.txt
echo "-----------------------" >> copy.txt
done
cat copy.txt
Changed the script after suggestion from #Kevin. Now the error message ./t.sh: syntax error at line 11: `$' unexpected
#!/bin/sh
truncate copy.txt
echo "Please enter the sentence you want to search:"
read inputVar
echo "Please enter the name of the file in which you want to search:"
read inputFileName
echo Please enter the number of lines you want to copy:
read inputLineNumber
[ -z "$inputLineNumber" ] || inputLineNumber=20
for N in $(grep -n $inputVar $inputFileName | cut -d ":" -f1)
do
LIMIT=$((N+inputLineNumber))
sed -n $N,${LIMIT}p $inputFileName >> copy.txt
echo "-----------------------" >> copy.txt
done
cat copy.txt
Try changing this line from:
[[-z "$inputLineNumber"]] || inputLineNumber=20
To this:
if [[ -z "$inputLineNumber" ]]; then
inputLineNumber=20
fi
Hope this helps.
Where to start...
You are running as /bin/sh but trying to use [[. [[ is a bash command that sh does not recognize. Either change the shebang to /bin/bash (preferred) or use [ instead.
You do not have a space between [[-z. That causes bash to read it as a command named [[-z, which clearly doesn't exist. You need [[ -z $inputLineNumber ]] (note the space at the end too). Quoting within [[ doesn't matter, but if you change to [ (see above), you will need to keep the quotes.
Your code says [[-z but your error says [-z. Pick one.
Use $(...) instead of `...`. The backticks are deprecated, and $() handles quoting appropriately.
You don't need to cat /dev/null >copy.txt, certainly not twice without writing to it in-between. Use truncate copy.txt or just plain >copy.txt.
You seem to have inconsistent quoting. Quote or escape (\x) anything with special characters (~, `, !, #, $, &, *, ^, (), [], \, <, >, ?, ', ", ;) or whitespace and any variable that could have whitespace. You don't need to quote string literals with no special characters (e.g. ":").
Instead of LIMIT=`expr...`, use limit=$((N+inputLineNumber)).

Need to add logic in Unix script convert from Windows to Unix format

I am having one script need to add logic that if some one add file from winscp and do not convert into plain text while transfer. so some time we get some special character (^m) in some value, i wanted to remove them
Here is my code.
cd $HOME_DIR
if [ $SHELL_STEP = 'step2' ]; then
if [ -s $DATA_DIR/$DATA_FILE.txt ]; then echo "The data file is present." cat -v new_reguest.txt $ awk '{ sub("\r$", ""); print }' new_request.txt > new_request.txt echo "Data file $DATA_FILE.txt found in $DATA_DIR directory." >> $LOG_FILE echo "" >> $LOG_FILE STATUS='good' else echo "The data file has not arrived yet." fi
if [ $STATUS = 'bad' ]; then
echo "The data file not found."
echo "The data file not found." >> $LOG_FILE
echo "" >> $LOG_FILE
SHELL_STEP='step5'
else
SHELL_STEP='step3'
fi
fi
I tried to using awk command, but it's not looking good.
please assist.
Most implementations will provide tools like dos2unix or d2u to remove carriage returns from the end of lines. You can use something like:
dos2unix new_request.txt >new_request_2.txt
mv new_request_2.txt new_request.txt
If you don't have the dos2unix command, you can do the same thing with sed:
sed -i 's/\r$//' new_request.txt
The -i is for in-place editing. If your version of sed doesn't have that, you'll have to resort to the same temporary file trick used in the dos2unix code above.

How to quote strings in file names in zsh (passing back to other scripts)

I have a script that has a string in a file name like so:
filename_with_spaces="a file with spaces"
echo test > "$filename_with_spaces"
test_expect_success "test1: filename with spaces" "
run cat \"$filename_with_spaces\"
run grep test \"$filename_with_spaces\"
"
test_expect_success is defined as:
test_expect_success () {
echo "expecting success: $1"
eval "$2"
}
and run is defined as:
#!/bin/zsh
# make nice filename removing special characters, replace space with _
filename=`echo $# | tr ' ' _ | tr -cd 'a-zA-Z0-9_.'`.run
echo "#!/bin/zsh" > $filename
print "$#" >> $filename
chmod +x $filename
./$filename
But when I run the toplevel script test_expect_success... I get cat_a_file_with_spaces.run with:
#!/bin/zsh
cat a file with spaces
The problem is the quotes around a file with spaces in cat_a_file_with_spaces.run is missing. How do you get Z shell to keep the correct quoting?
Thanks
Try
run cat ${(q)filename_with_spaces}
. It is what (q) modifier was written for. Same for run script:
echo -E ${(q)#} >> $filename
. And it is not bash, you don't need to put quotes around variables: unless you specify some option (don't remember which exactly)
command $var
always passes exactly one argument to command no matter what is in $var. To ensure that some zsh option will not alter the behavior, put
emulate -L zsh
at the top of every script.
Note that initial variant (run cat \"$filename_with_spaces\") is not a correct quoting: filename may contain any character except NULL and / used for separating directories. ${(q)} takes care about it.
Update: I would have written test_expect_success function in the following fashion:
function test_expect_success()
{
emulate -L zsh
echo "Expecting success: $1" ; shift
$#
}
Usage:
test_expect_success "Message" run cat $filename_with_spaces

Resources