0

sed command to delete everything and leave only words between pattern?

I tried:

$ sudo sed -i '/from/,/until/!d'

But it left some words under first line and it left whole lines not only words between patterns.

I have a file full of text but I only want to leave text between "from" text "until" and delete everything else.

I try

for file in `ls`
do
    echo "`awk '/from/,/until/' $file`" > $file
done

and i have left two lines one is text from pattern above one is empty new line

unknown
  • 17
  • Provide a sample of the contents of the file that you are trying to edit. – Nasir Riley Sep 03 '18 at 23:31
  • awk '/from/,/until/' filename > newfile – Kamaraj Sep 03 '18 at 23:34
  • i dont know filenames cant output to filename i need to do this to all files in folder sed -i infile command is good for that – unknown Sep 03 '18 at 23:35
  • 2
    @unknown. Would you please clarify the question. What do you want to do? What do you expect the final result? what is the content of the file? Do you want to change the content of the file or the file name? The question is completely unclear?! –  Sep 03 '18 at 23:44

1 Answers1

0

Sounds like you want to print everything between 2 patterns, but delete everything else. Something like this:

$ echo -e "a\nb\nc\nd\ne" | sed -ne '/b/,/d/p'
b
c
d

Where /b/ and /d/ are your starting and ending patterns. A similar approach can be accomplished using awk as well:

$ echo -e "a\nb\nc\nd\ne" | awk '/b/,/d/'
b
c
d

Patterns

When deciding what to use as your beginning/ending patterns you need to make sure you design them so that they're as explicit as possible.

For example:

$ cat afile
something
something
one
two
some start
start
what
did
you start
done
end
the end

Now to select lines that occur between lines that contain only the word /start/ followed by /done/:

$ sed -ne '/^start$/,/^done$/p' afile
start
what
did
you start
done

References

slm
  • 369,824
  • awk '/b/,/d/' file – slm Sep 03 '18 at 23:56
  • awk does not have such a feature. – slm Sep 04 '18 at 00:01
  • its create one empty line first line is correct but under make empty line and i need only one line – unknown Sep 04 '18 at 00:24
  • @unknown - can you please add some example input to your Q? It's hard to understand what's not working here. – slm Sep 04 '18 at 00:26
  • when i use awk with that command to print only text between two pattern and save it throught for loop function to all files in folder its create first line with correct text between pattern but add extra new line and i have two line first one is text from pattern second one is empty – unknown Sep 04 '18 at 00:34