Don
Don

Reputation: 235

Linux sed, how to delete the rest of the word?

Suppose I have text.txt:

342423423423 - 'namefile.jpg' saved (2423423kb/2423423kb)

I can use

sed 's/^.*- //' text.txt

the output will be:

'namefile.jpg' saved (2423423kb/2423423kb)

it will get rid the text at the beginning of that namefile.jpg, but what if I also want to get rid the rest of it ? I want the output to be like this:

'namefile.jpg'

What sed pattern should I use? Please note that after the 'namefile.jpg' the text isn't always the same. It changes from time to time.

Upvotes: 2

Views: 311

Answers (5)

Jotne
Jotne

Reputation: 41446

This is not sed but show how to do it with awk

awk -F\' '{print $2}' text.txt
namefile.jpg

or if you like to have the single quotes.

awk -F\' '{print FS$2FS}' text.txt
'namefile.jpg'

Upvotes: 2

Kalanidhi
Kalanidhi

Reputation: 5092

Try this way also

sed "s/.*\('.*'\).*/\1/" FileName

Output :

'namefile.jpg'

Upvotes: 2

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

Or with awk:

echo "342423423423 - 'namefile.jpg' saved (2423423kb/2423423kb)" | awk '{print $3}'

Default delimiter for awk is space. Just print the 3rd field.

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174696

You could use capturing groups.

sed 's/^.*- \([^ ]\+\).*/\1/' text.txt

OR

sed 's/^.*- //;s/ .*//' file
  • ^.*- regex matches all the characters from the start upto -. And the first command replaces all the matches characters with an empty string.

  • .* Now from the resultant string, this regex would match all the characters from the first space upto the last. Replacing those characters with an empty string will gave you the desired output.

Example:

$ echo "342423423423 - 'namefile.jpg' saved (2423423kb/2423423kb" | sed 's/^.*- \([^ ]\+\).*/\1/'
'namefile.jpg'
$ echo "342423423423 - 'namefile.jpg' saved (2423423kb/2423423kb" | sed 's/^.*- //;s/ .*//'
'namefile.jpg'

Upvotes: 3

Arnab Nandy
Arnab Nandy

Reputation: 6692

Just use a simple cut command

cut -d ' ' -f3 text.txt

or you can also use this,

sed 's/^.*- //' text.txt|cut -d ' ' -f1

Both will give you this Output:

'namefile.jpg'

Upvotes: 1

Related Questions