BASH Scripting - printing select lines in a file
Hello:
How do I print select lines in a file? I want to cycle through each line in a file, search for a digit in the 4th position, if greater than 3, then print the entire line. Before: 12 5 67 345 1 2356 34 2 43222 12 444 233145633 After: 12 5 67 345 2 43222 12 444 It only printed these two lines since the character in the 4th position was greater than 3. Thank you! |
Ok, that didn't display very well. I was trying to point out the fact that spaces are randomly interspersed throughout. Hopefully you get the point w/o the example.
|
Did you mean something like this?
Code:
#!/bin/bash |
homey:
It appears to be acting on the fourth word rather than the fourth character. Does that make sense? |
Perl is a little more suited to this sort of thing. You can do it from the command line here:
Code:
perl -n -e 'print if ( substr($_,3,1) > 3 );' file.txt |
How about this?
Code:
#!/bin/bash |
Quote:
|
You're right, perhaps this will work better. The original example didn't have alpha in it.
Code:
#!/bin/bash |
I thought that would result in error messages when $val was non-numeric, but it doesn't when we use double [[ ]] around the condition.
Another day, another thing learned. :) |
hello homey. perhaps we should use cases instead:
Code:
#!/bin/bash |
Thanks, that seems to work also.
Adding to my collection of notes ..... :) Edit: Actually, your code pointed out an error in mine. Where the file has many spaces, the echo statement needs quotes to handle spaces... echo "$line" Code:
#!/bin/bash |
Quote:
Code:
Before: |
Quote:
Anyway, a person could use -ge if they want to include 3 |
Code:
sed -n '/^...[4-9]/p' <file> |
What's up with: cat file.txt | \
Why not use: Code:
#!/bin/bash |
It's just up to you if you're up for speed. I find the first one a lot more common and readable though. You can't also use that normal syntax if you're going the use commands other than cat like sed or grep.
|
Shortest one so far I think...
Code:
grep '^...[3-9]' file.txt |
All times are GMT -5. The time now is 01:53 PM. |