0

I want to copy the line that have strings to another file

for eg

A file contain the below lines

ram 100 50
gopal 200 40
ravi 50 40
krishna 300 600
Govind 100 34

I want to copy the lines that has 100 or 200 to another file by skipping all the characters before (first occurrence in a line)100 or 200

I want it to copy 100 50 200 40 100 34 to another file

I am using sed -n '/100/p' filename > outputfile

can you please help me in adding lines with any one of the string using a single command

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
Vijay Asok
  • 17
  • 1
  • 7
  • 2
    Be careful you don't pick up lines that contain 51003, etc. (i.e. have numbers that contain 100 or 200 rather than ARE 100 or 200). All of the currently posted answers would fail that way. You should update your sample to include those cases and add the expected output. Also, do you want to search for `100` across the whole line or only within 1 or 2 specific space-separated fields on the line? If the latter then edit your example to show those cases you don't want to falsely match too. It's always trivial to find the matches but harder to not select similar lines that shouldn't match. – Ed Morton Sep 10 '17 at 19:50

3 Answers3

2

Short sed approach:

sed '/[12]00/!d; s/[^0-9[:space:]]*//g; s/^ *//g;' filename > outputfile
  • /[12]00/!d - exclude/delete all lines that don't match 100 or 200

  • s/[^0-9[:space:]]*//g - remove all characters except digits and whitespaces

The outputfile contents:

100 50
200 40
100 34
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • actually I have missed to add some details about my requirement. while copying I want to skip all the characters before first occurrence of 100 or 200 – Vijay Asok Sep 11 '17 at 14:29
1

This might work for you (GNU sed):

sed -n '/[12]00/w anotherFile' file

Only print if needed, write to anotherFile the regexp which matches 100 or 200.

potong
  • 55,640
  • 6
  • 51
  • 83
0

There are at least 2 possibilities:

sed -n '/100\|200/p' filename > outputfile

sed -n -e '/100/p' -e '/200/p' filename > outputfile

The latter is probably easier to remember and maintain (but maybe you should be using -f?), but note that it will print lines twice if they match both. You could fix this by using:

sed -n -e '/100/{p;b}' -e '/200/{p;b}' filename > outputfile

Then again, why are you using sed? This sounds like a job for grep.

o11c
  • 15,265
  • 4
  • 50
  • 75
  • actually I have missed to add some details about my requirement. while copying I want to skip all the characters before first occurrence of 100 or 200 – Vijay Asok Sep 11 '17 at 14:30
  • Note that `s///` has a `p` flag that works very similar to my second answer. – o11c Sep 12 '17 at 06:11