2

I want to remove everything from a file, such that only the numbers 1, 2, 3, 4, and 5 remain. Line breaks should be kept. How can I delete everything else from the file?

3 Answers 3

6

Something like this:

sed -i 's/[^1-5]//g' file

Here's a small test:

$ echo $'ab129c\n1d3e5fqq9cm3275\ncn730m271nv05482m1'
ab129c
1d3e5fqq9cm3275
cn730m271nv05482m1
$ echo $'ab129c\n1d3e5fqq9cm3275\ncn730m271nv05482m1'|sed 's/[^1-5]//g'
12
135325
3215421
3

tr should be more efficient than sed. Copying icyrock's test:

$ echo $'ab129c\n1d3e5fqq9cm3275\ncn730m271nv05482m1' | tr -dc "1-5\n"
12
135325
3215421

There's one disadvantage to tr, though: it can't do an in-place edit of an existing file (like sed -i does); if that's what you want you'd have to write to a temp file, then replace the original with that:

tr -dc "1-5\n" <file.txt >tempfile.txt && mv tempfile.txt file.txt
1
  • 1
    +1 for mentioning tr (though I consider myself advanced linux user, I don't remeber seeing it anywhere). Mar 16, 2012 at 4:42
1

I did it with:

sed -r 's/[^12345]//g' <file>

That will dump it to screen, and you can write to a file with:

sed -r 's/[^12345]//g' <file> > <new_file>

Or you could edit the file directly with

sed -i -r 's/[^12345]//g' <file>
2
  • 1
    Yeah, I saw yours did it without it. I tend to use it any time I'm using regex, even when it's simple enough to not need the full regex capabilities. I don't think it does any harm, it just isn't needed.
    – kingcoyote
    Mar 16, 2012 at 0:49
  • 1
    alias sedr="sed -r" :) Agree it's much easier to use with -r in many situations. Mar 16, 2012 at 0:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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