1

I have dataset as:

file.txt
de
fds
fds
a
sa
1
2
3
1
}

I would like to delete all the lines starting with characters or special characters. So my outfile is:

out.txt
1
2
3
1

I could do it manually with 'sed', but I am looking for a suitable command for this.

my code:

sed -i '/d//g' file.txt
sed -i '/f//g' file.txt
sed -i '/a//g' file.txt
sed -i '/s//g' file.txt
sed -i '/}//g' file.txt
Kay
  • 1,647
  • 2
  • 18
  • 40
  • Oops, you forgot to post your code! StackOverflow is about helping people fix their code. It's not a free coding service. Any code is better than no code at all. Meta-code, even, will demonstrate how you're thinking a program should work, even if you don't know how to write it. – ghoti Jun 09 '17 at 02:49
  • Thanks @ghoti for pointing out this. I have added my code. – Kay Jun 09 '17 at 02:56
  • See: [The Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/3776858) – Cyrus Jun 09 '17 at 03:08
  • `sed -n '/^[0-9]/p' file` – Cyrus Jun 09 '17 at 03:10

2 Answers2

2

Use grep with -E option for regex (or egrep in short):

grep -E "^[0-9].*" file.txt
RaphaMex
  • 2,509
  • 10
  • 25
  • 1
    No need for the `-E` for this regular expression. It's a BRE in addition to ERE. Also, you might want to consider defaulting to single quotes except in cases where you know you need to quote variables. Just a general safety measure and good habit. – ghoti Jun 09 '17 at 03:10
  • That's right, minimal answer would be "grep '^[0-9]' file.txt". However, I took the opportunity to show that grep could do more than that ;) – RaphaMex Jun 09 '17 at 03:16
  • @R.Saban .. Would you please suggest me a modification of this script, if I need to preserve the negative values. I have asked this question here https://stackoverflow.com/questions/45006897/remove-the-lines-starting-with-a-character-in-shell-but-preserve-the-negative-v – Kay Jul 10 '17 at 08:14
2

just keep lines starting with a number:

$ sed -i.bak -r '/^[0-9]/!d' filename

or delete lines starting with specific characters:

$ sed -i.bak -r '/^[dfas}]/d' filename
Weike
  • 1,052
  • 8
  • 12