I am newbie to UNIX. I came across this exercise in one the books.Can anyone help me with this question??????
Write a short Bash script that, given the name of a file as an argument,
reads the file name and creates a new file containing only lines which consist
of one word. Here is an example
This is a special text file
There
are 20 students in the class.
[TAB][SPACE] Nearly
half of them are enrolled in FoS. The rest are in
Faculty-Of-ES.
The output from the script should look like
There
[TAB][SPACE] Nearly
Faculty-Of-ES.
To read the file in '$1", you can simply cat "$1" but for the next requirement, write something with a loop that says:
#!/bin/bash
while read the_line; do
echo "$the_line"
done < "$1"
exit 0
From the example you wrote, you need to read every other line
#!/bin/bash
while read the_line; do
((i++%2)) && { echo "$the_line";}
done < "$1"
exit 0
i is a variable that's incremented ( i++ ) on every line read. i%2 returns 1 or 0, depending i is odd or even, basically, it returns 0 when i is 2; 4; 6; ...
And in sh/bash and many others scripting languages; zero means no errors.
No Errors: execute what's after the && , so echo "$the_line"
Thanks a lot to everyone!!!!!!!!!!!!
I will try the code and let you know...
Thanks again.
---------- Post updated at 05:19 AM ---------- Previous update was at 05:18 AM ----------
Hi Mr.itkamaraj,
This is not an assignment question. I am not studying at the moment. I am working as Support Engineer and learning bash scripting. I came across this question in some book and did not know the answer.