0

Suppose this the data.lst

Anil Sharma, Vaishali Nagar, science, 45, 67
Manoj Gupta, Sri Nagar Road, commerce, 66, 89
Kamal Sharma, Shastri Nagar, commerce, 81, 32
Rama Sharma, Vaishali Nagar, commerce, 45, 91
Chirag Harwani, Vaishali Nagar, science, 34, 63

and I want to write an awk script to show all the lines/records between the specified range, to be entered by the user.

This is what I have written so far,

desiredact.awk
BEGIN{
 printf "Enter the initial range: "
 getline n1 < "/dev/tty"
 printf "Enter the last range: "
 getline n2 < "/dev/tty"
 }

How to proceed further? Yes, ranges are the Line numbers.

6
  • 1
    Welcome to U&L! What have you tried? How did it not work as expected or intended? – DopeGhoti Jul 21 at 20:54
  • 1
    Range of what? Line numbers? If so, this can be done with sed: sed -n 3,5p data.lst prints lines 3, 4 and 5. Also, I second @DopeGhoti's request: Show us the program you have written so far. – berndbausch Jul 22 at 0:42
  • @DopeGhoti I've edited the questions kindly look. I don't know how to take line numbers (range) from users and then create a condition for the range. – JATIN Jul 22 at 6:19
  • @berndbausch Yes, line numbers. I've edited the question and have written the script. – JATIN Jul 22 at 6:21
  • 2
    Personally, I don't think you should use awk for user interaction if it can be avoided; in your case, I would acquire the ranges using a shell script and then call awk or sed with these ranges. To expand on your code: Check whether the current line is inside the range and print it when that's the case, e.g. NR>=n1 && NR<=n2 { print }. However, the sed code I suggested is better in my opinion, since more compact. – berndbausch Jul 22 at 6:45
0

It would be much easier to provide the start and end of the range desired to be output to awk as variables rather than try to parse them in-flight in the BEGIN block:

$ awk -v rangestart=3 -v rangeend=5 'NR >= rangestart && NR <= rangeend { print }' inputfile
Kamal Sharma, Shastri Nagar, commerce, 81, 32
Rama Sharma, Vaishali Nagar, commerce, 45, 91
Chirag Harwani, Vaishali Nagar, science, 34, 63

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.