Skip to content
Advertisement

sed command to copy lines that have strings

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

Advertisement

Answer

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
Advertisement