Home > Archive > Unix Programming > December 2006 > unix command question
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
unix command question
|
|
| chunji08@gmail.com 2006-12-18, 7:07 pm |
|
A text file may or may not has a keyword, Is there a way I can use a
line of unix command(s) to create a new text file, in which the line
that contains the keyword is moved to the first line ?
The one what I created is something like:
"
((cat old.txt | grep keyword ) && ( cat old.txt | grep -v keyword )) |
tee new.txt.
",
But it creates an empty "new.txt" file if the keyword does not exist in
the original file.
And idea ?
Charlie,
| |
| Chris F.A. Johnson 2006-12-18, 7:07 pm |
| On 2006-12-18, chunji08@gmail.com wrote:
>
> A text file may or may not has a keyword, Is there a way I can use a
> line of unix command(s) to create a new text file, in which the line
> that contains the keyword is moved to the first line ?
>
> The one what I created is something like:
> "
> ((cat old.txt | grep keyword ) && ( cat old.txt | grep -v keyword )) |
> tee new.txt.
> ",
>
> But it creates an empty "new.txt" file if the keyword does not exist in
> the original file.
line=$( grep keyword old.txt )
if [ -n "$line" ]
then
{
printf "%s\n" "$line"
grep -v keyword old.txt
} > new.txt
fi
--
Chris F.A. Johnson, author | <http://cfaj.freeshell.org>
Shell Scripting Recipes: | My code in this post, if any,
A Problem-Solution Approach | is released under the
2005, Apress | GNU General Public Licence
|
|
|
|
|