I have a file that looks like this:
2 xxxxxx
3 xxxxxxx xxx
....
(tab followed after the line number)
I need to add a range of lines to the file but not the ones existing already. So in a while loop I have a variable named LINE,
I'd need something like
grep "$LINE " file || echo "$line $othercontent" >> file
but it doesn't work; this works:
grep $LINE file || echo "$line $othercontent" >> file
However the pattern here is, say, "34 ", not "34".
How to use variable in grep /sed?
Oooh, regex patterns can be tricky.
There's nothing wrong with using grep "$pat", so I'm guessing that's not really a tab (either in the file or in the pattern string).
I think you can settle the issue with:
grep -qw "^$LINE" file
-q : quiet (the matching lines are not printed)
-w: word-matching (whole words only)
The carat "^" in the pattern will force $LINE to be at the beginning of the line, not just anywhere in the data.
Thanks gus2000 for your response. But this doesn't work (with the variable quoted:
grep -w '^$line' file
(or "^$line")
It works however:
grep -w $line file
^ is nice to have in this case, but again, how to make it all inside '...'? I used \$line & no luck as well.
Well, single-quotes will keep the variable from being expanded. Try:
echo "$LOGIN"
echo '$LOGIN'
Not quite the same! Strange that it doesnt work with the doublequotes. I think you can include the carat outside quotes like this:
grep -w ^$line file
but will probably splatter if "$line" is null.
you are right about the doube/single quoate!!
grep -w "$line" does work
however, grep -w "^$line" doesn't find the pattern. not sure why
Also, how to remove all the lines from the file with line range, say 1-150?
Thanks!